postgresql - Postgres Docker 镜像未使用自定义名称创建数据库

标签 postgresql docker docker-compose

postgres Docker 镜像的文档 says以下是关于环境变量 POSTGRES_DB 的内容:

This optional environment variable can be used to define a different name for the default database that is created when the image is first started. If it is not specified, then the value of POSTGRES_USER will be used.

我发现这根本不是真的。例如,使用此配置:

version: '3.7'

services:
  db:
    image: postgres:11.3-alpine
    restart: always
    container_name: store
    volumes:
      - postgres_data:/var/lib/postgresql/data/
    ports:
      - 5432:5432
    environment:
      - POSTGRES_USER=custom
      - POSTGRES_DB=customname
      - POSTGRES_PASSWORD_FILE=/run/secrets/db_password
    secrets:
      - db_password

volumes:
  postgres_data:

secrets:
  db_password:
    file: config/.secrets.db_password

默认数据库名为 postgres,而不是我指定的 customname:

$ docker exec -it store psql -U custom customname
psql: FATAL:  database customname does not exist
$ docker exec -it store psql -U custom postgres
psql (11.3)
Type help for help.

postgres=# ^D

我是否漏掉了一些明显的东西?

最佳答案

像您所做的那样提供环境变量,应该在容器初始化时创建 customname 数据库。无需在 /docker-entrypoint-initdb.d/ 的初始化脚本中创建用户名和数据库。

我会确保没有任何挂起的 postgres_data 卷。如果您之前在未指定环境变量的情况下启动了容器,则会为默认的 postgres 数据库创建卷。下次启动容器(指定 POSTGRES_DB 环境)时,将跳过数据库创建部分。

只是为了确保,删除任何创建的卷(名称应该类似于 *_postgres_data)

docker volume ls
docker volume rm <volume_name>

参见 User and DB were not created from environment variable arguments以及。希望有帮助

关于postgresql - Postgres Docker 镜像未使用自定义名称创建数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56657683/

相关文章:

sql - 带条件的 Postgresql LAG

ruby-on-rails - 如何在 Rails 中将 Squeel 与 hstore 一起使用

sql - PostgreSQL 在外键中使用常量

android - CircleCI CLI 为 Android SDK 寻找错误的路径

ssl - docker + SSL + apache2 + x509

docker - 使用cname而不是nameserver的IP地址运行docker容器dns标志

mysql - Docker-compose 为 spring 服务和 mysql 服务工作,但 init.sql 没有加载并且 Postman 返回空数据

postgresql - 如何在 LIKE 搜索中显式转换 ENUM 类型?

Docker compose/swarm 3 : docker file path , 构建、容器名称、链接、迁移

docker - 是否可以查看docker swarm内部DNS记录?