Unable to connect django conatiner with postgresql conatiner

I am trying to connect django and postgresql inside docker container I am unable to do that I have tried couple of things but nothing works for me following is my docker compose file

version: '3.8'
services:
  backend:
    build:
      context: .
      dockerfile: Dockerfile
    command: python manage.py runserver 0.0.0.0:8000
    ports:
      - 8000:8000
    volumes:
      - .:/app
    restart: on-failure
    depends_on:
      rabbitmq:
        condition: service_healthy

  postgres:
    image: postgres
    container_name: postgres
    volumes:
      - ./postgres-data:/var/lib/postgresql/data
    environment:
      - POSTGRES_DB=main
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=admin
    ports:
      - 5431:5431


  rabbitmq:
    image: rabbitmq:3-management
    container_name: rabbitmq
    hostname: rabbitmq
    ports:
      - 15673:15672

    environment:
      RABBITMQ_DEFAULT_USER: guest
      RABBITMQ_DEFAULT_PASS: guest
    healthcheck:
      test: rabbitmq-diagnostics check_port_connectivity
      interval: 30s
      timeout: 30s
      retries: 10
#  queue:
#    build:
#      context: .
#      dockerfile: Dockerfile
#    command: 'python consumer.py'
#    depends_on:
#      - db
#      - rabbitmq
#      - backend

In settings.py I have configuration like this:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'main',
        'USER': 'postgres',
        'PASSWORD': 'admin',
        'HOST': 'postgres',
        'PORT': '5431'
    }
}

Now when I run docker-compose up command I get the error "django.db.utils.OperationalError: could not translate host name "postgres" to address: Temporary failure in name resolution"

I also tried by changing host name to localhost in settings.py it then gives me this error "TCP/IP connections on port 5431?"

The current postgres image is using 5432 as default port tho https://hub.docker.com/_/postgres

Change it to 5432 instead

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'main',
        'USER': 'postgres',
        'PASSWORD': 'admin',
        'HOST': 'postgres',
        'PORT': '5432',
    }
}
Back to Top