简体   繁体   中英

Initialize postgres database (without using /docker-entrypoint-initdb.d)

I'm trying to initialize a database without using the entry point directory .

Here is a minimal Dockerfile:

FROM postgres:latest

POSTGRES_DB db
POSTGRES_USER user
POSTGRES_PASSWORD password

ADD db.sql /directory/
ADD script.sh /directory/

CMD ["sh", "/directory/script.sh"] 
# Or ENTRYPOINT ["/directory/script.sh"]?

And script.sh :

psql -d db -U user < /directory/db.sql

This does not work because postgres isn't up when the script is run.

How can I run db.sql without using /docker-entrypoint-initdb.d ?

If you look at the standard postgres image's entrypoint script the mechanism to support the /docker-entrypoint-initdb.d directory is pretty intricate: it needs to bootstrap the database directory and initial user and database, then it starts the database server in the background and runs everything in that directory, and finally runs the database for real. If you're trying to replicate this setup, you have to do all of these steps yourself.

There are other ways to set up a database, though. You can create an empty database and then run your application's migrations normally to create the initial schema. If you have an SQL file that normally you'd run against a database running the psql client tool, you can do the exact same thing with Docker

docker run -d -p 5432:5432 --name postgres postgres:12
psql -h localhost < db.sql

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM