Reputation: 2939
This question is related to this one: Docker - How can run the psql command in the postgres container?
But the solution provided above is only valid when you are doing things manually while here one would like to do things automatically using docker-compose.
So this docker container works:
FROM postgres
COPY init.sql /docker-entrypoint-initdb.d/
but this docker container fails:
FROM postgres
RUN psql -U postgres -c "CREATE USER user WITH PASSWORD 'pass';"
because by the time the RUN is executed the postgresql server has not started yet!
Is there a way to overcome this limitation?
Upvotes: 4
Views: 4632
Reputation: 2182
you can run some scripts in posgres when you mount the folder with your script to docker container at /docker-entrypoint-initdb.d/
se the docker-compose.yml that mounts the folder sql. The postgres images is awesome and will run the scripts each time the postgres starts...
version: '3.6'
services:
my_db:
image: postgres:alpine
volumes: ["/somepath/sql/:/docker-entrypoint-initdb.d/"]
the file structure of /somepath/
- docker-compose.yml
- sql
- new_extension.sql
and cat sql/new_extension.sql
/* create extension for cureent DB */
CREATE EXTENSION IF NOT EXISTS citext;
/* create extension over the template1 so all created databases after that also have the extension */
\c template1
CREATE EXTENSION IF NOT EXISTS citext;
Upvotes: 5