[Django]-Django connection to postgres by docker-compose

42๐Ÿ‘

โœ…

Each container in docker by default gets its own hostname and IP. When compose spins up the containers for you, it also places all of the containers on a network by default to permit DNS based discovery.

What this means is that your database is not reachable on localhost, but you can reach it by the service name โ€œdbโ€. Change this line in your settings.py:

    'HOST': 'localhost',

to:

    'HOST': 'db',
๐Ÿ‘คBMitch

4๐Ÿ‘

Hereโ€™s what worked for me:

in compose:

version: '3.7'
services: 
  web:
    build: .
    command: python /code/manage.py runserver 0.0.0.0:8000
    volumes: 
        - .:/code
    ports: 
        - 8000:8000
    environment: 
        - DB_HOST=db
        - DB_NAME=web
        - DB_USER=postgres
        - DB_PASSWORD=postgres

    depends_on: 
        - db

  db:
    image: postgres:12-alpine
    volumes: 
        - postgres_data:/var/lib/postgresql/data/
    environment: 
        - POSTGRES_DB=web
        - POSTGRES_USER=postgres
        - POSTGRES_PASSWORD=postgres
volumes:
   postgres_data:

in settings:

DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.postgresql',
    'NAME': os.environ.get('DB_NAME'),
    'USER':os.environ.get('DB_USER'),
    'PASSWORD': os.environ.get('DB_PASSWORD'),
    'HOST':os.environ.get('DB_HOST'),
    'PORT':5432,
 }
}
๐Ÿ‘คKhyar Ali

0๐Ÿ‘

Django settings.py -> Database={host:db} . Other database option remain same. Like

DATABASE_ENGINE=django.db.backends.postgresql
DATABASE_USER=postgres
DATABASE_PASSWORD=1234
DATABASE_NAME=pos
DATABASE_HOST=db
DATABASE_PORT=5432

Docker compose yml file: This settings created for Django, Nginx, Postgres

version: '3.8'
services:
  nginx:
    restart: unless-stopped
    build:
      context: .
      dockerfile: ./docker/nginx/Dockerfile
    ports:
      - '81:81'
    volumes:
      - static_volume:/home/pos/static/
      - ./docker/nginx/development:/etc/nginx/conf.d
    depends_on:
      - backend
  backend:
    restart: unless-stopped
    build:
      context: .
      dockerfile: ./docker/backend/Dockerfile
    image: pos-backend:backend # image_name: image_tag
    container_name: pos_backend
    volumes:
      - ./backend:/home/pos/
      - static_volume:/home/pos/static
      - media_volume:/home/pos/media
    environment:
      DJANGO_SETTINGS_MODULE: pos.settings
    ports:
      - "8000:8000"
    command: python manage.py runserver 0.0.0.0:8000
    expose:
      - 8000
    env_file:
      - ./backend/.env.dev
    depends_on:
      - db
  db:
    image: postgres:12
    container_name: pos_db
    volumes:
      - postgres_data:/var/lib/postgresql/data
    environment:
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=1234
      - POSTGRES_DB=pos
    ports:
      - '5432:5432'
    expose:
      - 5432
    networks:
      - default
volumes:
  static_volume: {}
  media_volume:
  postgres_data:
๐Ÿ‘คabdulalim

Leave a comment