[英]Connecting Django to Postgres: django.db.utils.OperationalError: FATAL: database "DATABASENAME" does not exist
[英]Connecting Django to Docker Postgres instance raising django.db.utils.OperationalError
我正在嘗試在我的本地機器上執行 django 項目,該項目需要 Postgres。
我對 docker 幾乎一無所知。 我從 docker 集線器中提取了 postgres 圖像,並按照 postgres docker 集線器頁面中的說明執行了以下命令。
$ docker run --name some-postgres -e POSTGRES_PASSWORD=mysecretpassword -d postgres
docker 容器已啟動:
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
402180487f68 postgres "docker-entrypoint.s…" 2 hours ago Up 2 hours 5432/tcp some-postgres
但我無法讓 Django 連接到它。 (Django 在我的本地機器上運行,而不是在 docker 上) Django 設置:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'postgres',
'USER': 'postgres',
'PASSWORD': 'mysecretpassword',
'HOST': 'localhost',
'PORT': 5432,
}
}
如果我使用上述設置執行遷移,錯誤是:
django.db.utils.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" (127.0.0.1) and accepting
TCP/IP connections on port 5432?
我假設連接沒有被拒絕,因為如果我停止容器,錯誤是一樣的。
一些教程/答案建議 HOST 應該是容器名稱。 對我來說這沒有多大意義,因為我不知道 Django 應該如何解決這個問題,但我還是嘗試了:
'HOST': 'some-postgres',
引發的錯誤是:
django.db.utils.OperationalError: could not translate host name "some-postgres" to address: nodename nor servname provided, or not known
我檢查了幾個問題和教程,但它們似乎都使用 docker-composer 和/或在 docker 中也有 django 項目。 仍然無法使項目連接到 postgres。
我相信您必須從 docker 轉發端口 5432: https://docs.docker.com/config/containers/container-networking
一個很好的類比是一個網絡服務器 - 假設您將在端口 8000 上的容器中啟動 django 應用程序。您不能簡單地打開 firefox 並從主機內導航到 localhost:8000,因為應用程序在隔離環境中運行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.