[英]python connect to postgres docker instance outside docker
我可以确认 docker 容器正在运行:
Name Command State Ports
-----------------------------------------------------------------------------------------------
adminer_1 entrypoint.sh docker-php-e ... Up 0.0.0.0:8080->8080/tcp
db_1 docker-entrypoint.sh postgres Up 5432/tcp
我也可以通过管理员连接到数据库(下图):
但后来我无法从 docker 与 Python 外部连接:
# import the connect library from psycopg2
from psycopg2 import connect
table_name = "trips"
# declare connection instance
conn = connect(
dbname = "postgres",
user = "postgres",
host = "localhost", #known ip 172.20.0.2
password = "password"
)
# declare a cursor object from the connection
cursor = conn.cursor()
# execute an SQL statement using the psycopg2 cursor object
cursor.execute(f"SELECT * FROM {table_name};")
# enumerate() over the PostgreSQL records
for i, record in enumerate(cursor):
print ("\n", type(record))
print ( record )
# close the cursor object to avoid memory leaks
cursor.close()
# close the connection as well
conn.close()
引发的错误:
psycopg2.OperationalError: could not connect to server: Connection refused
Is the server running on host "localhost" (::1) and accepting
TCP/IP connections on port 5432?
could not connect to server: Connection refused
Is the server running on host "localhost" (fe80::1) and accepting
TCP/IP connections on port 5432?
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?
在还尝试检查 ip 是否使用 postgres 正在监听:
docker inspect db_1 | grep "IPAddress"
"SecondaryIPAddresses": null,
"IPAddress": "",
"IPAddress": "172.20.0.2",
并将我的 python 脚本中的host
替换为172.20.0.2
,但我仍然无法连接。
您的 docker 容器“集合”只是将一个端口暴露(转发)给外界(也就是您的本地主机); 8080 是您的管理员网站。 因此,您可以做到这一点,并且与数据库位于同一内部网络上可以找到数据库,但由于端口未公开/转发,您无法访问数据库。
您将希望以与 web 端口相同的方式转发 DB 端口。 请注意,在您的第一个屏幕截图中,您可以看到 adminer_1 正在将 8080 转发到外部,而 db_1 没有转发。
如果您使用的是 docker-compose,您可能需要添加:
ports:
- "5432:5432"
到您的 postgres 容器规范。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.