I would like to create multiple databases at container startup. I use postgres:11.2
as base image.
After reading the doc here https://hub.docker.com/_/postgres and this post How to create User/Database in script for Docker Postgres, I am still unable to create multiple databases when the container starts.
I tried these solutions:
1st with init.sh
:
#!/bin/bash
set -e
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL
CREATE USER owner;
CREATE DATABASE productservice;
GRANT ALL PRIVILEGES ON DATABASE productservice TO owner;
CREATE DATABASE usersservice;
GRANT ALL PRIVILEGES ON DATABASE usersservice TO owner;
CREATE DATABASE financeservice;
GRANT ALL PRIVILEGES ON DATABASE financeservice TO owner;
CREATE DATABASE relationshipservice;
GRANT ALL PRIVILEGES ON DATABASE relationshipservice TO owner;
CREATE DATABASE securityservice;
GRANT ALL PRIVILEGES ON DATABASE securityservice TO owner;
EOSQL
And in the Dockerfile
ENV INIT_DIR /docker-entrypoint-initdb.d
RUN mkdir -p ${INIT_DIR}
COPY init.sh ${INIT_DIR}
I don't get any errors but neither the databases nor the user are created, only the default postgres
database is there.
2nd with init.sql
CREATE USER owner;
CREATE DATABASE productservice;
GRANT ALL PRIVILEGES ON DATABASE productservice TO owner;
CREATE DATABASE usersservice;
GRANT ALL PRIVILEGES ON DATABASE usersservice TO owner;
CREATE DATABASE financeservice;
GRANT ALL PRIVILEGES ON DATABASE financeservice TO owner;
CREATE DATABASE relationshipservice;
GRANT ALL PRIVILEGES ON DATABASE relationshipservice TO owner;
CREATE DATABASE securityservice;
GRANT ALL PRIVILEGES ON DATABASE securityservice TO owner;
And changed the Dockerfile
to
ENV INIT_DIR /docker-entrypoint-initdb.d
RUN mkdir -p ${INIT_DIR}
COPY init.sql ${INIT_DIR}
The result is the same as the first case.
Thanks for your help.
EDIT:
The complete Dockerfile
FROM postgres:11.2
ENV PGDATA /var/lib/postgresql/data/pgdata
ENV INIT_DIR /docker-entrypoint-initdb.d
RUN mkdir -p ${INIT_DIR}
COPY init.sql ${INIT_DIR}
RUN localedef -i fr_FR -c -f UTF-8 -A /usr/share/locale/locale.alias fr_FR.UTF-8
ENV LANG en_US.UTF-8
VOLUME ${PGDATA}