I have a Docker container that contains my Postgres database. It's using the official Postgres image which has a CMD entry that starts the server on the main thread.
I want to populate the database by running RUN psql –U postgres postgres < /dump/dump.sql
before it starts listening to queries.
I don't understand how this is possible with Docker. If I place the RUN
command after CMD, it will of course never be reached because Docker has finished reading the Dockerfile. But if I place it before the CMD
, it will run before psql even exists as a process.
How can I prepopulate a Postgres database in Docker?
After a lot of fighting, I have found a solution ;-)
For me was very useful a comment posted here: https://registry.hub.docker.com/_/postgres/ from "justfalter"
Anyway, I have done in this way:
db/structure.sql
is a sql dump, useful to initialize the first tablespace.Then, the
init_docker_postgres.sh
So finally:
Hope it helps!
There is yet another option available that utilises Flocker:
Alternatively, you can just mount a volume to /docker-entrypoint-initdb.d/ that contains all your DDL scripts. You can put in *.sh, *.sql, or *.sql.gz files and it will take care of executing those on start-up.
e.g. (assuming you have your scripts in /tmp/my_scripts)
I was able to load the data in by pre-pending the run command in the docker file with /etc/init.d/postgresql. My docker file has the following line which is working for me: