【发布时间】:2021-04-23 12:20:34
【问题描述】:
我可以确认 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?
还尝试使用 postgres 检查 ip 是否正在侦听:
docker inspect db_1 | grep "IPAddress"
"SecondaryIPAddresses": null,
"IPAddress": "",
"IPAddress": "172.20.0.2",
并用172.20.0.2替换了我的python脚本中的host,但我仍然无法连接。
【问题讨论】:
标签: python python-3.x postgresql docker