我正在使用 Docker 桌面的 Windows 10 機器上的 docker 容器內運行 postgres 資料庫。我想使用 psycopg2 在資料庫上運行 postgresql 查詢,但我無法建立與資料庫的連接。我使用以下命令運行資料庫
docker run --name thedatabase -p 5432:5432 -e POSTGRES_PASSWORD=postgres -e POSTGRES_HOST_AUTH_METHOD=md5 postgres:13.5
我曾經docker inspect獲取資料庫的 IP 地址。我使用以下代碼使用 psycopg2 建立與資料庫的連接。
import psycopg2
from psycopg2 import OperationalError
def create_connection(db_name, db_user, db_password, db_host, db_port):
connection = None
try:
connection = psycopg2.connect(
database=db_name,
user=db_user,
password=db_password,
host=db_host,
port=db_port,
)
print("Connection to PostgreSQL DB successful")
except OperationalError as e:
print(f"The error '{e}' occurred")
return connection
if __name__=="__main__":
connection = create_connection(
"thedatabase", "postgres", "postgres", "172.17.0.2", "5432"
)
我收到以下錯誤
The error connection to server at 172.17.0.2, port 5432 failed: Connection timed out (0x0000274C/10060) Is the server running on that host and accepting TCP/IP connections?
occurred
任何幫助,將不勝感激。謝謝。
uj5u.com熱心網友回復:
localhost如果您的 python 腳本未在 docker 中執行,請嘗試替換 docker ip 。
if __name__=="__main__":
connection = create_connection(
"thedatabase", "postgres", "postgres", "localhost", "5432"
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/423122.html
標籤:
