When you try to build a Django development environment with docker while looking at Quickstart: Compose and Django and `docker-compose up` I got the following error:
django.db.utils.OperationalError: could not translate host name "db" to address: Name or service not known
setting.py
setting.py
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'postgres',
        'USER': 'postgres',
        'PASSWORD': 'postgres',
        'HOST': 'db',
        'PORT': 5432,
    }
}
Docker-compose.yml
version: '3'
services:
  web:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    depends_on:
      - db
  db:
    image: postgres
docker-compose.yml
version: '3'
services:
    web:
        build: .
        command: python3 manage.py runserver 0.0.0.0:8000
        volumes:
            - .:/code
        ports:
            - "8000:8000"
        depends_on:
            - db
    db:
        image: postgres
        ports: 
            - "5432"
        environment:
          - POSTGRES_DB=postgres
          - POSTGRES_USER=postgres
          - POSTGRES_PASSWORD=postgres
The error is now gone.
To use postgres within Docker, you need to configure information such as database user, password, and db-name. This can be done by setting the container's environment variables in the environment in the modified `` `dokcer-compose.yml```.
Recommended Posts