[PYTHON] When I try to connect django and postgresql with Docker, I get the error "django.db.utils.OperationalError: could not translate host name" db "to address: Name or service not known"

error

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 before modification

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

Modified docker-compose.yml

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

When I try to connect django and postgresql with Docker, I get the error "django.db.utils.OperationalError: could not translate host name" db "to address: Name or service not known"
When I try to install mysqlclient with Django, I get error: command'gcc' failed with exit status 1.
When I try to connect to MySQL with mysql-connector-python, I cannot connect with the error "SSL connection error: SSL_CTX_set_tmp_dh failed"
When I try to update the data on DynamoDB with Python (boto3), I get "ExpressionAttributeNames contains invalid key: Syntax error; key: <key name>"
When I try to import pandas on macOS I get the error No module named'_bz2'
I get [Error 2055] when trying to connect to MySQL on Heroku
Check when the Docker container does not connect to the Internet
Get the host name of the host PC with Docker on Linux
When I try to run the pip command after updating pip, I get "No such file or directory"
When I try to execute the make command of Makefile with os / exec of golang, the second and subsequent executions result in an error.
I get an error when trying to install maec 4.0.1.0 with pip