gpt4 book ai didi

docker-compose 并在初始化时在 Postgres 中创建数据库

转载 作者:行者123 更新时间:2023-12-02 18:45:51 27 4
gpt4 key购买 nike

我有个问题。我对 docker 很陌生,所以我想要做的是创建一个 docker-compose 文件,该文件在 compose 命令上也将创建数据库。问题是它没有像我问的那样创建数据库。所以我的 docker-compose 看起来像:

version: '3'

services:
db:
image: postgres:latest
restart: always
ports:
- 5432:5432
environment:
POSTGRES_PASSWORD: 'postgres'
volumes:
- database_data:/var/lib/postgresql/data
- ./init.sql:/docker-entrypoint-initdb.d/init.sql

volumes:
database_data:
driver: local

当我在日志中启动 docker-compose up 时,我可以看到
db_1  | PostgreSQL Database directory appears to contain a database; Skipping initialization
db_1 |
db_1 | 2020-01-13 11:14:36.259 UTC [1] LOG: starting PostgreSQL 12.1 (Debian 12.1-1.pgdg100+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 8.3.0-6) 8.3.0, 64-bit
db_1 | 2020-01-13 11:14:36.259 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432
db_1 | 2020-01-13 11:14:36.260 UTC [1] LOG: listening on IPv6 address "::", port 5432
db_1 | 2020-01-13 11:14:36.264 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
db_1 | 2020-01-13 11:14:36.277 UTC [29] LOG: database system was shut down at 2020-01-13 11:10:57 UTC
db_1 | 2020-01-13 11:14:36.280 UTC [1] LOG: database system is ready to accept connections

在我的 init SQL 中只有 1 行:
CREATE DATABASE "MyDataBase";

当我列出 DB 是 Postgres 容器时,我的 DB 无处可寻。这个问题的根源是什么?

最佳答案

根据documentation of postgres docker image你做的一切都是正确的。

If you would like to do additional initialization in an image derived from this one, add one or more *.sql, *.sql.gz, or *.sh scripts under /docker-entrypoint-initdb.d (creating the directory if necessary). After the entrypoint calls initdb to create the default postgres user and database, it will run any *.sql files, run any executable *.sh scripts, and source any non-executable *.sh scripts found in that directory to do further initialization before starting the service.



但是,根据您上面发布的日志,我认为您错过了一个问题。

Warning: scripts in /docker-entrypoint-initdb.d are only run if you start the container with a data directory that is empty; any pre-existing database will be left untouched on container startup.



所以,我会尝试清空 database_data目录并再次运行 docker-compose up .

关于docker-compose 并在初始化时在 Postgres 中创建数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59715622/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com