[英]Django doesn't connect to postgresql database using docker-compose
Yes i know this question has been asked, and the usual error is making the DB_HOST = docker service name, in my case db
.是的,我知道有人问过这个问题,通常的错误是使 DB_HOST = docker 服务名称,在我的例子中是
db
。
Here's my docker-compose.yml
:这是我的
docker-compose.yml
:
version: "3"
services:
db:
image: postgres:latest
restart: always
ports:
- "54320:5432"
expose:
- "54320"
volumes:
- ./database-data:/var/lib/postgresql/data/ # persist data even if container shuts down
environment:
- POSTGRES_DB=postgres
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=postgres
# POSTGRES_HOST_AUTH_METHOD: trust
django:
build: ./api
restart: always
command: ["python", "manage.py", "runserver", "0.0.0.0:8000"]
volumes:
- ./api:/app/api
ports:
- "8000:8000"
depends_on:
- db
raddl_admin:
build: ./frontend/raddl_admin
stdin_open: true # docker run -i
tty: true # docker run -t
command: ["npm", "start"]
ports:
- "3000:3000"
volumes:
- ./frontend/raddl_admin:/app/frontend/raddl_admin
- /app/frontend/raddl_admin/node_modules
volumes:
database-data: # named volumes can be managed easier using docker-compose
Logging the django
service gives:记录
django
服务给出:
django.db.utils.OperationalError: could not connect to server: Connection refused
Is the server running on host "db" (172.18.0.2) and accepting
TCP/IP connections on port 54320?
So it's clearly trying to connect to db
on that port and my environment vars are set for the django instance.所以它显然是在尝试连接到该端口上的
db
,并且我的环境变量是为 django 实例设置的。
I can even ping my db
service from my django service
:我什至可以从我的
django service
db
docker exec -it 1f764333ace2 bash | ping db
PING db (23.221.222.250): 56 data bytes
64 bytes from 23.221.222.250: icmp_seq=0 ttl=50 time=42.055 ms
64 bytes from 23.221.222.250: icmp_seq=1 ttl=50 time=42.382 ms
6
Why can't I connect to the db service from Django?为什么我无法从 Django 连接到 db 服务?
Ah, so my issue was with the port number.啊,所以我的问题是端口号。 For some reason, keeping the db exposed port to "5432" resolved this.
出于某种原因,将数据库暴露端口保持为“5432”解决了这个问题。 I thought that it would have conflicted with my host's localhost instance of postgres.
我认为它会与我主机的 postgres 本地主机实例发生冲突。 I guess not.
我猜不会。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.