我正在尝试从 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/