[英]Django cannot connect to postgresql docker container
I have a postgres db running in a docker container:我有一个在 docker 容器中运行的 postgres 数据库:
my docker-compose:我的 docker-compose:
version: "3"
services:
db:
image: postgres:13.1-alpine
environment:
- POSTGRES_DB=mydb
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=test
ports:
- "5432:5432"
volumes:
- ./postgres_data:/var/lib/postgresql/data/
Django running on the host machine (ubuntu linux, not in the docker container) cannot connect to it.在宿主机上运行的 Django(ubuntu linux,不在 docker 容器中)无法连接到它。
django's settings.py: django的settings.py:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'HOST' : "localhost",
'NAME' : "mydb",
'USER' : "postgres",
'PASSWORD' : "test",
'PORT':5432,
}
}
Exception:例外:
django.db.utils.OperationalError: could not connect to server: No such file or directory
Is the server running locally and accepting
connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"
Database is certainly avaliable on port 5432(I can connect to it with dbeaver database client on localhost:5432).数据库当然在端口 5432 上可用(我可以使用 localhost:5432 上的 dbeaver 数据库客户端连接到它)。
What could be the cause of the problem?问题的原因可能是什么?
Access it as HOST=db
in stead of localhost
assuming that the django is also contained in the docker-compose.yml假设 django 也包含在 docker-compose.yml 中,以HOST=db
而不是localhost
访问它
This is because in your docker-compose the database "service" name is db
and therefore its "DNS" name will be db
within the docker-compose created network.这是因为在您的 docker-compose 中,数据库“服务”名称为db
,因此其“DNS”名称将在 docker-compose 创建的网络中为db
。
figured it out, just had an error in settings.py connection values想通了,只是在 settings.py 连接值中有错误
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.