【问题标题】:PostgreSQL not accessible from within a Docker container无法从 Docker 容器中访问 PostgreSQL
【发布时间】:2019-07-05 16:45:32
【问题描述】:

我在从 Python 应用程序连接到 PostgreSQL 时遇到了一些问题。 PostgreSQL 在容器之外,因为它是一个现有的数据库。

从容器外部,数据库看起来可以访问:

$ nmap -p 5432 localhost
Starting Nmap 7.70 ( https://nmap.org ) at 2019-07-05 18:33 CEST
Nmap scan report for localhost (127.0.0.1)
Host is up (0.00014s latency).
Other addresses for localhost (not scanned): ::1

PORT     STATE SERVICE
5432/tcp open  postgresql

Nmap done: 1 IP address (1 host up) scanned in 0.12 seconds

但从内部:

bash-4.4# nmap -p 5432 localhost
Starting Nmap 7.70 ( https://nmap.org ) at 2019-07-05 16:34 UTC
Nmap scan report for localhost (127.0.0.1)
Host is up (0.000040s latency).
Other addresses for localhost (not scanned): ::1

PORT     STATE  SERVICE
5432/tcp closed postgresql

Nmap done: 1 IP address (1 host up) scanned in 0.41 seconds

我找不到任何类似的问题。

【问题讨论】:

标签: postgresql docker networking


【解决方案1】:

在运行你的 python 容器时添加 --network="host" :

快速启动一个 postgres 服务器:

docker run --rm -d --name postgres-server -p 5432:5432 postgres

如果我尝试使用 docker 客户端连接它,如果没有 --network="host",它将失败:

docker run --rm -it --name postgres-client postgres psql -Upostgres -h localhost
psql: could not connect to server: connection refused

使用--network:

docker run --rm -it --name postgres-client --network="host" postgres psql -Upostgres -h localhost
psql (10.4 (Debian 10.4-2.pgdg90+1)
postgres=#

干杯

【讨论】:

  • 完美运行,谢谢。我没有意识到网络也是容器化的。
猜你喜欢
  • 2018-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-18
  • 2018-08-09
  • 1970-01-01
  • 2021-07-19
  • 2020-06-05
相关资源
最近更新 更多