Postgresql-12

無法連接到 docker 容器內的 postgres

  • September 17, 2021

我已經啟動了一個新的postgres:12docker 實例:

$ docker run -it -d --name newdb \
   -p 5444:5432 \
   -e POSTGRES_PASSWORD=postgres \
   -e POSTGRES_USER=postgres \
   --volumes-from dbstore \
   -v /mnt/data/dbbackup:/backup postgres:12 bash \
   -c "cd /dbtestdata && tar xvf /backup/20210206_backup.tar --strip 1 && /bin/bash"

然後我附上它:

$ docker exec -it newdb /bin/bash

創建了一個集群:

# pg_createcluster 12 main

這導致:

Creating new PostgreSQL cluster 12/main ...
/usr/lib/postgresql/12/bin/initdb -D /var/lib/postgresql/12/main --auth-local peer --auth-host md5
The files belonging to this database system will be owned by user "postgres".
This user must also own the server process.

The database cluster will be initialized with locale "en_US.utf8".
The default database encoding has accordingly been set to "UTF8".
The default text search configuration will be set to "english".

Data page checksums are disabled.

fixing permissions on existing directory /var/lib/postgresql/12/main ... ok
creating subdirectories ... ok
selecting dynamic shared memory implementation ... posix
selecting default max_connections ... 100
selecting default shared_buffers ... 128MB
selecting default time zone ... Etc/UTC
creating configuration files ... ok
running bootstrap script ... ok
performing post-bootstrap initialization ... ok
syncing data to disk ... ok

Success. You can now start the database server using:

   pg_ctlcluster 12 main start

Ver Cluster Port Status Owner    Data directory              Log file
12  main    5432 down   postgres /var/lib/postgresql/12/main /var/log/postgresql/postgresql-12-main.log

啟動服務:

# service postgresql restart
[ ok ] Restarting PostgreSQL 12 database server: main.

嘗試了兩種連接方式,但都沒有成功:

# psql -U postgres
psql: error: FATAL:  Peer authentication failed for user "postgres"

# psql -U postgres -W
Password: ******* <<-- postgres
psql: error: FATAL:  Peer authentication failed for user "postgres"

我做錯了什麼?

postgres對等身份驗證取決於執行的 linux/unix 使用者與參數psql中的使用者相同。-U postgres當您在本地以 root 執行時,這是不正確的。

postgres容器外的使用者不必映射到postgres容器內的使用者。

建議更改身份驗證機制

我有一個類似的設置,我想在 postgres docker 上執行 psql。為此,我執行了以下命令:

docker exec -t --user <db_user> <container_name> psql -U <db_user>
e.g.
docker exec -t --user postgres postgres_db_1 psql -U postgres

這給了我終端中的互動式 psql。

我發現要修復psql: error: FATAL: Peer authentication failed for user "postgres"錯誤,我必須為我的 docker 容器指定 postgres 使用者

引用自:https://dba.stackexchange.com/questions/284855