Home > Back-end >  Is the server running on host "db" (172.28.0.2) and accepting TCP/IP connections on port 5
Is the server running on host "db" (172.28.0.2) and accepting TCP/IP connections on port 5

Time:04-05

django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "db" (172.28.0.2) and accepting TCP/IP connections on port 5432?

docker-compose

version: '3.9'

services:
  backend:
    build: ./backend
    command: sh -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000"
    volumes:
      - ./backend:/app/backend
    ports:
      - "8000:8000"
    env_file:
      - backend/.env.dev
    depends_on:
      - db
  db:
    image: postgres:14-alpine
    volumes:
      - postgres_data:/var/lib/postgresql/data/
    ports:
      - "5432:5432"
    env_file:
      - backend/.env.dev
volumes:
  postgres_data:

Dockerfile:

FROM python:3.9.10-alpine

ENV PYTHONUNBUFFERED 1
WORKDIR /app/backend
COPY requirements.txt /app/backend
RUN pip install --upgrade pip
RUN apk add --update --no-cache postgresql-client
RUN apk add --update --no-cache --virtual .tmp-build-deps \
      gcc libc-dev linux-headers postgresql-dev
RUN pip install -r requirements.txt
RUN apk del .tmp-build-deps 

EXPOSE 8000
CMD ["python3", "manage.py", "runserver", "0.0.0.0:8000"]

Database setting:

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.postgresql_psycopg2",
        "NAME": os.environ.get("POSTGRES_DB"),
        "USER": os.environ.get("POSTGRES_USER"),
        "PASSWORD": os.environ.get("POSTGRES_PASSWORD"),
        "HOST": os.environ.get("POSTGRES_HOST"),
        "PORT": 5432,
    }
}

.env :

POSTGRES_USER=user
POSTGRES_PASSWORD=password
POSTGRES_DB=my_db
POSTGRES_HOST=db
  

CodePudding user response:

Use docker-compose networks

docker-compose.yml:

version: 3.9

services:
  backend:
    build: ./backend
    command: sh -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000"
    volumes:
      - ./backend:/app/backend
    networks:
      - backend
    ports:
      - "8000:8000"
    env_file:
      - backend/.env.dev
    depends_on:
      - db
  db:
    image: postgres:14-alpine
    volumes:
      - postgres_data:/var/lib/postgresql/data/
    ports:
      - "5432:5432"
    networks:
      - backend
    env_file:
      - backend/.env.dev
volumes:
  postgres_data:

networks:
  backend:
     driver: bridge

I guess it work.

CodePudding user response:

Are you running Django on your local machine or inside of the docker?

If you're trying to run it on your local machine, just use localhost instead of the container name db for your POSTGRES_HOST env variable.

But, I'm not sure about the exact reason. Can you share the logs via docker logs backend and docker logs db?

  • Related