Problems with Quickstart: Compose and Django

I have followed up this manual https://docs.docker.com/compose/django/

My docker-compose.yml

version: '3'

services:
  db:
    image: postgres
  web:
    build: .
    command: python3 manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    depends_on:
      - db

setting.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'postgres',
        'USER': 'postgres',
        'HOST': 'db',
        'PORT': 5432,
    }
}

When I run using docker-compose up everything is fine.

But when I run using python manage.py runserver I got this error
psycopg2.OperationalError: could not translate host name "db" to address: Name or service not known

Maybe I have wrong postgre configuration? Can anyone help me?

When you create a stack, Docker will create some stack-internal networks and an internal “dns” to resolve the services host name. The db in the settings.py is referring to the db: in the docker-compose.yml and is resolved within the stack itself.

Since both the web: service and the db: service is running in the same stack, they can see each other without any other configuration.

If you want to runt the Django Server outside of the stack (but why would you…) you need to expose the port 5432 from the db: service first, get the IP from that running service and use that one as HOST configuration instead of db. And that is why you don’t want to run the Django server outside of the stack. :wink:

1 Like

Thanks for explanation

Thanks for the description. This is very useful. I’m in this situation where I want to the use the django development server for more rapid iterations on changes vs the docker build time and app setup steps. My postgres for django is in a docker container though. Now I understand the error message. Thank you