我从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
我找不到任何类似的问题。
答案 0 :(得分: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=#
欢呼