简体   繁体   中英

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 .

Here's my 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.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.

I can even ping my db service from my django service :

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?

Ah, so my issue was with the port number. For some reason, keeping the db exposed port to "5432" resolved this. I thought that it would have conflicted with my host's localhost instance of postgres. I guess not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM