Using docker-compose to create tables in postgresql database

后端 未结 3 1789
渐次进展
渐次进展 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:35

    I would create the tables as part of the build process. Create a new Dockerfile in a new directory ./database/

    FROM postgres:latest
    COPY . /fixtures
    WORKDIR /fixtures
    RUN /fixtures/setup.sh
    

    ./database/setup.sh would look something like this:

    #!/bin/bash
    set -e
    
    /etc/init.d/postgresql start
    psql -f create_fixtures.sql    
    /etc/init.d/postgresql stop
    

    Put your create user, create database, create table sql (and any other fixture data) into a create_fixtures.sql file in the ./database/ directory.

    and finally your postgres service will change to use build:

    postgres:
        build: ./database/
        ...
    

    Note: Sometimes you'll need a sleep 5 (or even better a script to poll and wait for postgresql to start) after the /etc/init.d/postgresql start line. In my experience either the init script or the psql client handles this for you, but I know that's not the case with mysql, so I thought I'd call it out.

提交回复
热议问题