Docker 以“信任”模式运行 PostgreSQL

Mam*_*oru 3 postgresql docker docker-compose

我目前正在学习 docker 并尝试使用 PostgreSQL 数据库运行 docker 容器。我成功了一次,一切似乎都很顺利。一段时间后,我尝试运行另一个具有几乎相同设置的 Docker 容器,但是,它没有按预期进行。我的问题是,现在,每当我尝试运行 PostgreSQL 容器时,initdb都会以“信任”模式初始化数据库,并接受任何没有密码的连接。

\n

到目前为止,我已经尝试从控制台运行命令:

\n
docker run --name some-postgres -e POSTGRES_PASSWORD=mysecretpassword -p 32000:5432 -d postgres:14.5-alpine\n
Run Code Online (Sandbox Code Playgroud)\n

以及运行docker-compose.yaml

\n
services:\n  db:\n    container_name: Test_container\n    image: postgres:14.5-alpine\n    restart: unless-stopped\n    ports:\n      - "32000:5432"\n    environment:\n      POSTGRES_USER: postgres\n      POSTGRES_PASSWORD: mysecretpassword\n
Run Code Online (Sandbox Code Playgroud)\n

此外,我尝试以不同的方式排序标签、不同的图像和不同的值,清理docker:删除所有容器、图像和卷,甚至重新安装docker,但是,每当我检查新创建的容器的日志时,我都会得到:

\n
sh: locale: not found\n2022-08-16 09:35:50.709 UTC [30] WARNING:  no usable system locales were found\nperforming post-bootstrap initialization ... ok\ninitdb: warning: enabling "trust" authentication for local connections\nYou can change this by editing pg_hba.conf or using the option -A, or\n--auth-local and --auth-host, the next time you run initdb.\nsyncing data to disk ... ok\n
Run Code Online (Sandbox Code Playgroud)\n

我的假设之一是,由于某种原因,docker 看不到我指定的密码,因此以“信任”模式启动数据库,但是,如果我添加

\n
environment:\n      POSTGRES_USER: postgres\n      POSTGRES_PASSWORD: postgres\n      POSTGRES_DB: test_db\n
Run Code Online (Sandbox Code Playgroud)\n

docker-compose.yaml中,正在创建test_db 数据库。

\n

我很感激任何关于如何使 docker 运行 PostgreSQL 容器而不是在“信任”模式下的建议,因为如果指定了密码,默认情况下它应该是这样。

\n
\n

Juan Gonz\xc3\xa1lez指出:

\n
\n

注 1:PostgreSQL 映像在本地设置信任身份验证,因此您可能会注意到从本地主机(在同一容器内)连接时不需要密码。但是,如果从不同的主机/容器连接,则需要密码。

\n
\n

因此,根据文档,我更新了我的docker-compose.yaml文件:

\n
environment:\n      POSTGRES_USER: postgres\n      POSTGRES_PASSWORD: postgres\n      POSTGRES_DB: test_db\n      POSTGRES_HOST_AUTH_METHOD: scram-sha-256\n      POSTGRES_INITDB_ARGS: --auth-host=scram-sha-256\n
Run Code Online (Sandbox Code Playgroud)\n

并再次尝试交换顺序和/或删除POSTGRES_INITDB_ARGS,但数据库仍然以“信任”模式运行。

\n

Mam*_*oru 5

正如 @jjanes 在我的问题的评论中指出的那样,解决方案是添加POSTGRES_INITDB_ARGS: --auth=scram-sha-256将设置本地和主机类型的连接。