postgresql - initialize postgres container from docker-compose file
问题描述
I am trying to start a postgres container form docker-compose file and also initialize it.
docker-compose.yml
version: "3"
postgres:
image: "postgres"
command: bash -c "
postgres &&
createuser -l \"auser\"
"
My goal is: 1) start postgres container 2) create a user
The current implementation fails with the following error
"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.
解决方案
不允许 PostgreSQL 服务器的“root”执行。
您不应该使用root
用户运行数据库容器。更好地运行postgres
用户。
一种方法是在 docker-compose.yml 中指定用户。
postgres:
image: postgres
container_name: postgres
user: postgres
ports:
- "5432:5432"
command: 'postgres'
但是再次
command: bash -c "
postgres &&
createuser -l \"auser\"
"
在创建用户命令期间,可能存在数据库包含未准备好接受连接的情况。
所以你有两个最好的选择。
- 使用环境变量
POSTGRES_USER
此可选环境变量用于
POSTGRES_PASSWORD
设置用户及其密码。此变量将创建具有超级用户权限的指定用户和同名数据库。如果未指定,则将使用 postgres的默认用户。
postgres:
image: postgres
container_name: postgres
environment:
POSTGRES_USER: test
POSTGRES_PASSWORD: password
POSTGRES_DB: myapp
user: postgres
ports:
- "5432:5432"
第二种选择
初始化脚本
如果您想在从该图像派生的图像中进行额外的初始化,请在
*.sql, *.sql.gz, or *.sh scripts
下面 添加一个或多个/docker-entrypoint-initdb.d
(必要时创建目录)。在入口点调用 initdb 以创建默认的 postgres 用户和数据库后,它将运行 any*.sql files
,运行任何可执行*.sh
脚本,并在该目录中找到任何非可执行*.sh
脚本以在启动服务之前进行进一步的初始化。
例如,要添加额外的用户和数据库,请将以下内容添加到/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