我使用以下 docker-compose.yml 檔案:
version: '3.8'
services:
db:
image: postgres:13-alpine
volumes:
- postgres_data:/var/lib/postgresql/data/
expose:
- 5432
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=postgres
- POSTGRES_DB=testdb
volumes:
postgres_data:
我提出來docker-compose up -d --build。現在,當我嘗試從 Python 訪問它時,比如說,使用 psycopg2 出現以下錯誤
>>> conn = psycopg2.connect(host="localhost", database="testdb", user="postgres", password="postgres")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.9/site-packages/psycopg2/__init__.py", line 122, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: connection to server at "localhost" (::1), port 5432 failed: Connection refused
Is the server running on that host and accepting TCP/IP connections?
connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused
Is the server running on that host and accepting TCP/IP connections?
>>> conn = psycopg2.connect(host="db", database="testdb", user="postgres", password="postgres")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.9/site-packages/psycopg2/__init__.py", line 122, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: could not translate host name "db" to address: nodename nor servname provided, or not known
你能幫我解決這個問題嗎?
uj5u.com熱心網友回復:
問題是expose沒有將埠發布到主機。它們只能被鏈接的服務訪問。
您必須手動發布埠:
docker-compose run -d -p 5432:5432 db
uj5u.com熱心網友回復:
您應該從 docker-compose.yml 檔案中洗掉公開選項并添加埠選項,例如:
ports:
-"5432:5432"
然后您可以localhost從您的應用程式通過主機連接到資料庫。
uj5u.com熱心網友回復:
而不是使用暴露我們這個:
ports:
- "5432:5432"
這定義了轉發到 docker 容器的埠
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/390045.html
標籤:Python PostgreSQL的 码头工人 docker-compose psycopg2
