Django Is the server running on host "localhost" (127.0.0.1) and accepting web-1 | TCP/IP connections on port 5432?

Viewed 48

I am trying to dockerize my Django project. I have the following config files:

Dockerfile:

FROM python:3.9-bullseye

WORKDIR /app

ENV PYTHONUNBUFFERED=1

COPY csgo .

RUN apt-get update -y \
    && apt-get upgrade -y pip \
    && pip install --upgrade pip \
    && pip install -r requirements.txt

CMD ["python", "manage.py", "runserver", "127.0.0.1:8000"]

My docker-compose.yml looks like:

version: '3'

services:
  web:
    build:
      context: .
      dockerfile: Dockerfile
    env_file:
      - csgo.env
    volumes:
      - .:/code
    ports:
      - 8000:8000
    depends_on:
      - db

  db:
    image: postgres:13
    restart: always
    ports:
      - 5432:5432
    env_file:
      - csgo.env
    environment:
      - POSTGRES_PASSWORD=postgres
      - DB_NAME=postgres
      - DB_USER=postgres
      - DB_PASSWORD=postgres
      - DB_HOST=localhost
    volumes:
      - ./db/psql-init/db.sql:/docker-entrypoint-initdb.d/db.sql
      - postgres_data:/var/lib/postgresql/data/

volumes:
  postgres_data:

When I try to docker-compose up I get this error:

django.db.utils.OperationalError: could not connect to server: Connection refused
csgo-web-1    |         Is the server running on host "localhost" (127.0.0.1) and accepting
csgo-web-1    |         TCP/IP connections on port 5432?
csgo-web-1    | could not connect to server: Cannot assign requested address
csgo-web-1    |         Is the server running on host "localhost" (::1) and accepting
csgo-web-1    |         TCP/IP connections on port 5432?

What could be the problem? Can you explain what it means by Is the server running on host "localhost" and why it wouldn't accept connection on port 5432?

Ports available:

com.docke 14554 user  149u  IPv6 0xd0180dc2abc35a25      0t0    TCP *:5432 (LISTEN)
1 Answers

Under db in your docker compose file, replace the ports section with expose eg

expose:
 - 5432

This will ensure your web app can access the db within the docker network. Only the port mapping should be done for the web app as it should be accessible from the host machine.

Related