postgresql - docker容器启动时如何通过psql(-h localhost -p 5432)连接到postgres

标签 postgresql docker docker-compose

我有一些 docker-compose.yml 文件。在这个文件中定义了数据库服务(postgres:9.6):

db:
image: postgres:9.6
volumes:
  - ./test/data/postgresql/:/var/lib/postgresql/data:delegated
  - ./test/bootstrap/postgres:/docker-entrypoint-initdb.d:delegated
ports:
  - 15432:5432
environment:
  - POSTGRES_DB=test
  - POSTGRES_USER=test
  - PGDATA=/var/lib/postgresql/data/testdata

还有一些 sh ​​脚本位于 ./test/bootstrap/postgres。在这个脚本中,我尝试像这样通过 psql 连接到 postgres:psql -U "$POSTGRES_USER"-d "$POSTGRES_DB"-h localhost -p 5432 (我知道 -h localhost -p 5432不是必需的,但我需要它)。
当我的容器启动时发生错误:

psql: could not connect to server: Connection refused 
   Is the server running on host "localhost" (127.0.0.1) and accepting 
   TCP/IP connections on port 5432? 

但在此之后我重新启动(在第一次启动此脚本后未执行)我的数据库容器然后在容器内手动运行 sh 脚本并成功执行。即使是第一次启动,它也可以连接到本地主机和端口 5432。

如果我像 psql -U "$POSTGRES_USER"-d "$POSTGRES_DB"这样的脚本连接,则没有连接错误。

谁能给我解释一下这种奇怪的行为?为什么当容器启动时我无法连接到 localhost:5432 但如果从容器手动连接它连接成功?

谢谢!

最佳答案

我的理解是,在容器初始化期间,服务器正在监听 Unix 域套接字。

LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"

docker-entrypoint-init.d 目录中的脚本在服务器在此模式下运行时执行。您正在尝试通过指定 -h localhost 通过 TCP/IP 进行连接。 尝试删除该参数以使用 Unix 套接字连接到服务器。

关于postgresql - docker容器启动时如何通过psql(-h localhost -p 5432)连接到postgres,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50613035/

相关文章:

java - 我可以将 Realm 用作 postgres ORM 吗?

node.js - docker Express 服务器之间的连接被拒绝

mongodb - 带有mongod的ENTRYPOINT和CMD命令导致未知的选项错误

docker - HAProxy Docker Container无法使用localhost在我的Cockroach DB Docker容器之间进行负载平衡

postgresql - Gcloud Sql postgres 时区问题

sql - 动态 SQL PostgreSQL

mysql - 使用 docker-compose 来创建 MySQL 模式/数据库

docker - 无法在 Windows 10 中启动 Docker 容器

sql - PostgreSQL : Aggregate multiple rows from a table into a single record

linux - 如何从 docker 容器管理主机网络命名空间