Using docker-compose to create tables in a postgresql database

I am using docker-compose to deploy a multi-configuration python Flask application. I find it difficult to understand how to create tables in the postgresql database at build time, so I do not need to add them manually using psql.

My docker-compose.yml file:

web:
  restart: always
  build: ./web
  expose:
    - "8000"
  links:
    - postgres:postgres
  volumes:
    - /usr/src/flask-app/static
  env_file: .env
  command: /usr/local/bin/gunicorn -w 2 -b :8000 app:app

nginx:
  restart: always
  build: ./nginx/
  ports:
    - "80:80"
  volumes:
    - /www/static
  volumes_from:
    - web
  links:
    - web:web

data:
  restart: always
  image: postgres:latest
  volumes:
    - /var/lib/postgresql
  command: "true"

postgres:
  restart: always
  image: postgres:latest
  volumes_from:
    - data
  ports:
    - "5432:5432"

I do not want to enter psql for input:

CREATE DATABASE my_database;
CREATE USER this_user WITH PASSWORD 'password';
GRANT ALL PRIVILEGES ON DATABASE "my_database" to this_user;
\i create_tables.sql

I would appreciate a guide on creating tables.

+16
source share
2 answers

I do not want to enter psql for input

You can simply use the built-in container initialization mechanism:

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

This ensures that your sql will be executed after the database server loads correctly.

script. psql /docker-entrypoint-initdb.d/ , .sh, .sql .sql.gz.

10- , ASCII. , , 20-create-tables.sql 30-seed-tables.sql.gz, , .

, . , , , docker-compose, .sql DB.

, build. Docker Compose , , , build, init, /docker-entrypoint.sh docker, /docker-entrypoint-initdb.d/.

+18

. Dockerfile ./database/

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

./database/setup.sh :

#!/bin/bash
set -e

/etc/init.d/postgresql start
psql -f create_fixtures.sql    
/etc/init.d/postgresql stop

, , sql ( ) create_fixtures.sql ./database/.

, , postgres build:

postgres:
    build: ./database/
    ...

. /etc/init.d/postgresql start sleep 5 ( script postgresql). , init script, psql, , mysql, , .

+10

Source: https://habr.com/ru/post/1676509/


All Articles