postgresql - 从 docker-compose 文件初始化 postgres 容器

标签 postgresql docker docker-compose dockerfile

我正在尝试从 docker-compose 文件启动一个 postgres 容器并对其进行初始化。

docker-compose.yml

version: "3"
  postgres:
  image: "postgres"
  command: bash -c "
   postgres &&
   createuser -l \"auser\"
   "

我的目标是: 1)启动postgres容器 2)创建用户

当前的实现失败并出现以下错误

"root" execution of the PostgreSQL server is not permitted.
The server must be started under an unprivileged user ID to prevent
possible system security compromise.  See the documentation for
more information on how to properly start the server.

最佳答案

"root" execution of the PostgreSQL server is not permitted.

您不应该使用 root 用户运行数据库容器。最好运行 postgres 用户。

一种方法是在 docker-compose 中指定用户。

postgres:
  image: postgres
  container_name: postgres
  user: postgres
  ports:
    - "5432:5432"
  command: 'postgres'

但是再次

  command: bash -c "
   postgres &&
   createuser -l \"auser\"
   "

在创建用户命令期间,可能存在数据库包含尚未准备好接受连接的情况。

所以你有两个最佳选择。

  • 使用环境变量

POSTGRES_USER

This optional environment variable is used in conjunction with POSTGRES_PASSWORD to set a user and its password. This variable will create the specified user with superuser power and a database with the same name. If it is not specified, then the default user of postgres will be used.

postgres:
  image: postgres
  container_name: postgres
  environment:
    POSTGRES_USER: test
    POSTGRES_PASSWORD: password
    POSTGRES_DB: myapp
  user: postgres
  ports:
    - "5432:5432"

第二种选择

初始化脚本

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.

例如,要添加其他用户和数据库,请将以下内容添加到/docker-entrypoint-initdb.d/init-user-db.sh:

#!/bin/bash
set -e

psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL
    CREATE USER docker;
    CREATE DATABASE docker;
    GRANT ALL PRIVILEGES ON DATABASE docker TO docker;
EOSQL

关于postgresql - 从 docker-compose 文件初始化 postgres 容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58258624/

相关文章:

sql - Postgresql 9.0 中的反向 FK 约束?

postgresql - 寻找匹配 Tindr 风格 - 将 2 个用户配对在一起,可以批准或拒绝匹配

docker - 我的图像中是否包含 FROM 图像层

docker - docker 容器内的 I2C

Docker GELF 记录附加字段

sql - 没有 CTE 的 Postgres/PADB 中的递归自查询

python - 使用 Django + Postgres 进行加密的策略?

linux - 如何生成主机唯一 ID?

docker-compose - docker-compose使用gitlab-ci引发错误

Docker 镜像文件夹权限未更新