繁体   English   中英

docker postgres 使用 network=host 的连接错误

[英]Connection Error with docker postgres using network=host

问题

我无法连接到在笔记本电脑上的 docker 映像中运行的 PostgreSQL 数据库(14.1/最新版本)。 我正在尝试使用在笔记本电脑上的另一个容器中运行的 .NET EntityFrameworkCore/Npgsql 和直接在笔记本电脑上运行的psql连接到数据库。

环境

  • macOS 10.15.7
  • Docker 台式机 4.3.2 (72729)

重新创建

我像这样启动我的 postgres 容器。 请注意,由于它处于主机网络模式,因此我不发布端口。

docker run -d --network=host --name=my-database -v dbdata:/var/lib/postgresql/data -e POSTGRES_PASSWORD=postgres postgres
docker ps
CONTAINER ID   IMAGE      COMMAND                  CREATED         STATUS         PORTS      NAMES
18e154fe815c   postgres   "docker-entrypoint.s…"   4 minutes ago   Up 4 minutes   5432/tcp   my-database

来自my-database容器的日志显示

...
2022-01-11 16:56:18.179 UTC [1] LOG:  starting PostgreSQL 14.1 (Debian 14.1-1.pgdg110+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit
2022-01-11 16:56:18.179 UTC [1] LOG:  listening on IPv4 address "0.0.0.0", port 5432
2022-01-11 16:56:18.179 UTC [1] LOG:  listening on IPv6 address "::", port 5432
2022-01-11 16:56:18.182 UTC [1] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
2022-01-11 16:56:18.188 UTC [26] LOG:  database system was shut down at 2022-01-11 16:35:54 UTC
2022-01-11 16:56:18.203 UTC [1] LOG:  database system is ready to accept connections

此时我希望能够连接到数据库,但出现错误。

$ psql -h localhost -p 5432 -U postgres
psql: error: connection to server at "localhost" (::1), port 5432 failed: Connection refused
        Is the server running on that host and accepting TCP/IP connections?
connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused
        Is the server running on that host and accepting TCP/IP connections?

我真的不能说我明白这里发生了什么,但是在尝试了许多标志组合之后,这就是让我能够按预期连接的原因

docker run -d --rm -p5432:5432 --name=my-datbase -v dbdata:/var/lib/postgresql/data -e POSTGRES_PASSWORD=postgres postgres

显然,这与我上面提出的策略不同,因为它消除了--network=host参数,而是发布了它的端口。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM