python连接到docker外部的postgres docker实例
我可以确认docker容器正在运行:python连接到docker外部的postgres docker实例,python,python-3.x,postgresql,docker,Python,Python 3.x,Postgresql,Docker,我可以确认docker容器正在运行: Name Command State Ports ----------------------------------------------------------------------------------------------- adminer_1 entrypoint.sh docker-php-e ... Up 0.0.0
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
我还可以通过adminer连接到db(下图):
但我无法从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脚本中的主机
,但我仍然无法连接。您的docker容器“集合”仅向外部世界公开(转发)一个端口(即您的本地主机);8080是您的管理员网站。因此,您可以访问该数据库,并且与数据库位于同一内部网络上的数据库可以找到该数据库,但是您无法访问该数据库,因为端口未公开/转发
您将希望以与web端口相同的方式转发DB端口。注意,在第一个屏幕截图中,您可以看到adminer_1正在将8080转发到外部,而db_1没有转发
如果您正在使用docker compose,则可能需要添加:
ports:
- "5432:5432"
符合您的postgres容器规格。正确!这就解决了问题,非常感谢。