Could not translate host name "db" to address: Name or service not known

I'm using Django + Docker and when building the image of one of my projects I'm facing problems when running the command:

docker-compose run web python manage.py makemigrations

error:

root@debian:/home/suportenpd1/Documentos/setorT# docker-compose run web python manage.py makemigrations
[+] Creating 1/0
 ✔ Container setort-db-1  Created                                                                                                                                                                             0.0s 
[+] Running 1/1
 ✔ Container setort-db-1  Started                                                                                                                                                                             1.1s 
/usr/local/lib/python3.12/site-packages/django/core/management/commands/makemigrations.py:160: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': could not translate host name "db" to address: Name or service not known

  warnings.warn(
No changes detected

docker-compose.yml:

services:
  db:
    image: postgres:15.6
    volumes:
      - ./data/db:/var/lib/postgresql/data
    environment:
      - POSTGRES_DB=setorT
      - POSTGRES_USER=setorT
      - POSTGRES_PASSWORD=setorT@2024$
    ports:
      - "5432:5432"
  web:
    build: .
    command: ["./wait-for-it.sh", "db:5432", "--", "python", "manage.py", "runserver", "0.0.0.0:8000"]
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    environment:
      - POSTGRES_NAME=setorT
      - POSTGRES_USER=setorT
      - POSTGRES_PASSWORD=setorT@2024$
    depends_on:
      - db

setting.py:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': os.environ.get('POSTGRES_NAME'),
        'USER': os.environ.get('POSTGRES_USER'),
        'PASSWORD': os.environ.get('POSTGRES_PASSWORD'),
        'HOST': 'db',
        'PORT': 5432,
    }
}

The command you specify in docker-compose run <service> <command> overrides the command you specify in service definition YAML. See: https://docs.docker.com/reference/cli/docker/compose/run/.

In your case, you're overriding:

command: ["./wait-for-it.sh", "db:5432", "--", "python", "manage.py", "runserver", "0.0.0.0:8000"]

with:

python manage.py makemigrations

I suspect that your wait-for-it.sh script halts your web container until the DB is fully initialized and ready to handle queries. Add a call to wait-for-it.sh to your docker-compose run and you should be fine.

Back to Top