Using docker-compose to create tables in postgresql database

后端 未结 3 1807
渐次进展
渐次进展 2020-12-23 01:59

I am using docker-compose to deploy a multicontainer python Flask web application. I\'m having difficulty understanding how to create tables in the postgresql database durin

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-23 02:46

    I dont want to have to enter psql in order to type in

    You can simply use container's built-in init mechanism:

    COPY init.sql /docker-entrypoint-initdb.d/10-init.sql

    This makes sure that your sql is executed after DB server is properly booted up.

    Take a look at their entrypoint script. It does some preparations to start psql correctly and looks into /docker-entrypoint-initdb.d/ directory for files ending in .sh, .sql and .sql.gz.

    10- in filename is because files are processed in ASCII order. You can name your other init files like 20-create-tables.sql and 30-seed-tables.sql.gz for example and be sure that they are processed in order you need.

    Also note that invoking command does not specify the database. Keep that in mind if you are, say, migrating to docker-compose and your existing .sql files don't specify DB either.

    Your files will be processed at container's first start instaed of build stage though. Since Docker Compose stops images and then resumes them, there's almost no difference, but if it's crucial for you to init the DB at build stage I suggest still using built-in init method by calling /docker-entrypoint.sh from your dockerfile and then cleaning up at /docker-entrypoint-initdb.d/ directory.

提交回复
热议问题