使用docker-compose在postgresql数据库中创建表

bla*_*lah 29 postgresql docker docker-compose

我正在使用docker-compose来部署多容器python Flask Web应用程序.我在构建期间难以理解如何在postgresql数据库中创建表,所以我不必用psql手动添加它们.

我的docker-compose.yml文件是:

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"
Run Code Online (Sandbox Code Playgroud)

我不想输入psql才能输入:

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
Run Code Online (Sandbox Code Playgroud)

我很感激如何创建表格的指导.

Dae*_*ndt 32

我不想输入psql才能输入

您可以简单地使用容器的内置init机制:

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

这可确保在正确启动DB服务器后执行sql.

看看他们的入口点脚本.它做了一些准备工作正确启动psql并查找/docker-entrypoint-initdb.d/目录中的文件结尾.sh,.sql.sql.gz.

10-在filename中是因为文件是按ASCII顺序处理的.你能说出你的其他的init文件,如20-create-tables.sql30-seed-tables.sql.gz例如,并确保他们在需要的顺序进行处理.

另请注意,调用命令指定数据库.如果您正在迁移到docker-compose并且现有.sql文件也未指定DB ,请记住这一点.

您的文件将在容器的第一个启动build阶段处理.由于Docker Compose停止了图像然后恢复它们,几乎没有区别,但是如果在build阶段初始化数据库至关重要,我建议仍然使用内置的init方法,通过/docker-entrypoint.sh从dockerfile 调用然后清理/docker-entrypoint-initdb.d/目录.

  • 这不适用于最新版本的postgres图片:( (2认同)

Vic*_* Di 19

在Dockerfile中使用COPY方法对我不起作用。但是我设法通过添加以下内容来运行init.sql文件:

volumes:
    - ./init.sql:/docker-entrypoint-initdb.d/init.sql
Run Code Online (Sandbox Code Playgroud)

进入我的docker-compose.yml。init.sql与我的docker-compose.yml位于同一目录中。我在这里偷看了解决方案:https : //gist.github.com/vrulevskyi/307b08abddc9568cf8f9c1b429c1ab56


dne*_*hin 9

我会创建表作为构建过程的一部分.Dockerfile在新目录中创建新的./database/

FROM postgres:latest
COPY . /fixtures
WORKDIR /fixtures
RUN /fixtures/setup.sh
Run Code Online (Sandbox Code Playgroud)

./database/setup.sh 看起来像这样:

#!/bin/bash
set -e

/etc/init.d/postgresql start
psql -f create_fixtures.sql    
/etc/init.d/postgresql stop
Run Code Online (Sandbox Code Playgroud)

将您的create user,create database,create table sql(以及任何其他fixture数据)放入目录中的create_fixtures.sql文件中./database/.

最后你的postgres服务将改为使用build:

postgres:
    build: ./database/
    ...
Run Code Online (Sandbox Code Playgroud)

注意:有时您需要一行sleep 5(甚至更好的脚本来轮询并等待postgresql启动)/etc/init.d/postgresql start.根据我的经验,init脚本或psql客户端为你处理这个,但我知道mysql不是这样,所以我想我会把它叫出来.

  • 我添加了`RUN chmod + x / fixtures / setup.sh`,解决了这个问题。我现在得到`不存在PostgreSQL集群;参见“ man pg_createcluster”……(警告)。psql:无法连接到服务器:没有这样的文件或目录服务器是否在本地运行并且在Unix域套接字“ /var/run/postgresql/.s.PGSQL.5432”上接受连接?服务'postgres'构建失败:命令'/ bin / sh -c /fixtures/setup.sh'返回了非零代码:2` (3认同)