Could not translate host name “db” to address: Temporary failure in name resolution

Hi team

I am not sure I must ask for help about this topic here in this great forum, but I really need help, I spent a lot of time browsing on internt to find a solution but not success. If his is not the place to post this, just help me to delete or disregard this post.

I have a project in Django and Python 3.10 running on Docker image.
all of this is running on Ubuntu 22.04.2 LTS, and

Below you could find the docker-compose.yml and settings.py information so you can see how both file as configure in ubuntu server.

The issue I have (and after searching on internet and reading a lot I was not able to fix) is that every time I execute the python manage.py runserver or python manage.py migrate I am getting the following error message.

If you need any further information let me know so I can provide it to you. Thanks in advance for your help. any suggestion will be really appreciated.

settings.py


"""
Django settings for platecplatform project.

Generated by 'django-admin startproject' using Django 4.1.

For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""

from pathlib import Path
import os

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-$r1f%xgpnxe!xd)$ueoobm-7i6of2^1xmo1_drk76pxd6ldzat'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*', '10.229.156.239', '172.17.61.1', '10.251.55.112']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'rest_framework',
    'django_admin_listfilter_dropdown',

    'equipamentos',
    'ocorrencias',
    'gestao_competencia',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'platecplatform.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates/')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'platecplatform.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases

dev = os.getenv('dev', False)

if not dev: DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': os.getenv('POSTGRES_DB'),
        'USER': os.getenv('POSTGRES_USER'),
        'PASSWORD': os.getenv('POSTGRES_PASSWORD'),
        'HOST': 'db',
        #'HOST': '10.187.6.154',
        'PORT': 5432
    }
}

else: DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}



# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/

LANGUAGE_CODE = 'pt-BR'

TIME_ZONE = 'America/Sao_Paulo'

USE_I18N = True

USE_TZ = False


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/

STATIC_URL = 'static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]


# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'


"""
REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
    'PAGE_SIZE': 20
}
"""

docker-compose.yml

version: "3"

services:
  web:
    container_name: web
    build: .
    restart: always
    environment:
    - POSTGRES_DB=platec
    - POSTGRES_USER=platec
    - POSTGRES_PASSWORD=platec
    ports: 
      - "8000:8000"
      - "8501:8501"
    volumes:
      - .:/app/

  db:
    container_name: db
    image: postgres
    environment:
    - POSTGRES_DB=platec
    - POSTGRES_USER=platec
    - POSTGRES_PASSWORD=platec
    restart: always
    volumes:
      - bancodedadospg:/var/lib/postgresql/data
    ports:
      - 5432:5432

volumes:
  bancodedadospg:
    external: true

finally the error I am getting every time I run python manage.py runserver

(venv) platec@platecbd:~/production$ python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
Exception in thread django-main-thread:
Traceback (most recent call last):
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/db/backends/base/base.py", line 282, in ensure_connection
    self.connect()
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner
    return func(*args, **kwargs)
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/db/backends/base/base.py", line 263, in connect
    self.connection = self.get_new_connection(conn_params)
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner
    return func(*args, **kwargs)
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/db/backends/postgresql/base.py", line 215, in get_new_connection
    connection = Database.connect(**conn_params)
  File "/home/platec/production/venv/lib/python3.10/site-packages/psycopg2/__init__.py", line 122, in connect
    conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: could not translate host name "db" to address: Temporary failure in name resolution


The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/platec/.asdf/installs/python/3.10.5/lib/python3.10/threading.py", line 1016, in _bootstrap_inner
    self.run()
  File "/home/platec/.asdf/installs/python/3.10.5/lib/python3.10/threading.py", line 953, in run
    self._target(*self._args, **self._kwargs)
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 137, in inner_run
    self.check_migrations()
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/core/management/base.py", line 564, in check_migrations
    executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/db/migrations/executor.py", line 18, in __init__
    self.loader = MigrationLoader(self.connection)
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/db/migrations/loader.py", line 58, in __init__
    self.build_graph()
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/db/migrations/loader.py", line 235, in build_graph
    self.applied_migrations = recorder.applied_migrations()
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/db/migrations/recorder.py", line 81, in applied_migrations
    if self.has_table():
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/db/migrations/recorder.py", line 57, in has_table
    with self.connection.cursor() as cursor:
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner
    return func(*args, **kwargs)
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/db/backends/base/base.py", line 323, in cursor
    return self._cursor()
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/db/backends/base/base.py", line 299, in _cursor
    self.ensure_connection()
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner
    return func(*args, **kwargs)
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/db/backends/base/base.py", line 281, in ensure_connection
    with self.wrap_database_errors:
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/db/utils.py", line 91, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/db/backends/base/base.py", line 282, in ensure_connection
    self.connect()
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner
    return func(*args, **kwargs)
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/db/backends/base/base.py", line 263, in connect
    self.connection = self.get_new_connection(conn_params)
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner
    return func(*args, **kwargs)
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/db/backends/postgresql/base.py", line 215, in get_new_connection
    connection = Database.connect(**conn_params)
  File "/home/platec/production/venv/lib/python3.10/site-packages/psycopg2/__init__.py", line 122, in connect
    conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
django.db.utils.OperationalError: could not translate host name "db" to address: Temporary failure in name resolution

Not sure, but I think you might need to add

depends_on: db

To the web section of your docker compose file

Hi @czue

thanks for replying to me.
I already had tried to add that line of code into the docker-compose.yml inside the “Web” service just below of volumes, (as below detail).
But it did not worke. I continue getting the same message.

services:
  web:
    container_name: web
    build: .
    restart: always
    environment:
    - POSTGRES_DB=platec
    - POSTGRES_USER=platec
    - POSTGRES_PASSWORD=platec
    ports: 
      - "8000:8000"
      - "8501:8501"
    volumes:
      - .:/app/
     depends_on: 
      - db

Is the compose file at the top the complete file, or are there other definitions in it?
If it’s not the complete file, please post it.

It may help to see the web container Dockerfile.

I’m not sure I understand what I’m looking at here for that traceback. Is that an attempt to run runserver in the container or outside?
If this is something you’re trying to do outside the container, then no - your local runserver is not going to have access to the container-based name db.

Hi, Ken,

About the this question: Is the compose file at the top the complete file, or are there other definitions in it? → for both settings.py and docker-compose.yml I posted here the entire files as I have on the server, none line was missed here. (see de docker file and docker-entrypoint.sh below)

Dockerfile

FROM python:3.10 as base

# Set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

RUN python -m pip install --upgrade pip

# Install os-level dependencies (as root)
RUN apt-get update && apt-get install -y -q --no-install-recommends build-essential \
  # cleaning up unused files to reduce the image size
  && apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false \
  && rm -rf /var/lib/apt/lists/*

# Create a directory for the source code and use it as base path
WORKDIR /app

COPY requirements.txt /app/requirements.txt

RUN mkdir -p /app/assets \
    && mkdir -p /app/logs \
    && chmod 755 /app \
    && pip install --no-cache-dir -r /app/requirements.txt

# Install python packages at system level
RUN pip install --no-cache-dir -r requirements.txt

COPY . /app/

RUN chmod +x docker-entrypoint.sh

ENTRYPOINT ["/app/docker-entrypoint.sh"]

docker-entrypoint.sh

#!/bin/bash

# apply database migrations
python ./manage.py migrate --noinput

# collect static files
# python manage.py collectstatic --noinput

sh dashboard.sh &

PYTHONDONTWRITEBYTECODE=1 python ./manage.py runserver 0.0.0.0:8000

# Start Gunicorn processes
#echo Starting Gunicorn.

#exec gunicorn app.wsgi:application \
#    --name app \
#    --bind 0.0.0.0:80 \
#    --workers 3 \
#    --log-level=info \
#    --log-file=/src/logs/gunicorn.log \46
#    --access-logfile=/src/logs/access.log \
#    "$@"

On the other hand, I think I was trying to exec python manage.py outside the docker, I meant directly from my pyCham console while docker image was running. But I also down the docker image and got the same error: So I am not what to do now :frowning:

What I am trying to do is to remove some fields from a model that I already had in my Django project. I commented those fields from my model, then directly on PyCharm I exec python manage.py makemigrations

So far, so good.

(venv) platec@platecbd:~/production$ python manage.py makemigrations
/home/platec/production/venv/lib/python3.10/site-packages/django/core/management/commands/makemigrations.py:143: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': could not translate host name "db" to address: Temporary failure in name resolution

  warnings.warn(
Migrations for 'ocorrencias':
  ocorrencias/migrations/0005_remove_ocorrenciaplatec_atendimento_finalizado_and_more.py
    - Remove field atendimento_finalizado from ocorrenciaplatec
    - Remove field nome_responsavel from ocorrenciaplatec
    - Remove field precisa_MBR from ocorrenciaplatec

The issue is when I tried to exec python manage.py migrate, then I got the same error message I mentioned on my first comment.


(venv) platec@platecbd:~/production$ python manage.py makemigrations
/home/platec/production/venv/lib/python3.10/site-packages/django/core/management/commands/makemigrations.py:143: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': could not translate host name "db" to address: Temporary failure in name resolution

  warnings.warn(
Migrations for 'ocorrencias':
  ocorrencias/migrations/0005_remove_ocorrenciaplatec_atendimento_finalizado_and_more.py
    - Remove field atendimento_finalizado from ocorrenciaplatec
    - Remove field nome_responsavel from ocorrenciaplatec
    - Remove field precisa_MBR from ocorrenciaplatec
(venv) platec@platecbd:~/production$ python manage.py migrate
Traceback (most recent call last):
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/db/backends/base/base.py", line 282, in ensure_connection
    self.connect()
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner
    return func(*args, **kwargs)
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/db/backends/base/base.py", line 263, in connect
    self.connection = self.get_new_connection(conn_params)
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner
    return func(*args, **kwargs)
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/db/backends/postgresql/base.py", line 215, in get_new_connection
    connection = Database.connect(**conn_params)
  File "/home/platec/production/venv/lib/python3.10/site-packages/psycopg2/__init__.py", line 122, in connect
    conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: could not translate host name "db" to address: Temporary failure in name resolution


The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/platec/production/manage.py", line 22, in <module>
    main()
  File "/home/platec/production/manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line
    utility.execute()
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/core/management/base.py", line 402, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/core/management/base.py", line 448, in execute
    output = self.handle(*args, **options)
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/core/management/base.py", line 96, in wrapped
    res = handle_func(*args, **kwargs)
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/core/management/commands/migrate.py", line 114, in handle
    executor = MigrationExecutor(connection, self.migration_progress_callback)
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/db/migrations/executor.py", line 18, in __init__
    self.loader = MigrationLoader(self.connection)
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/db/migrations/loader.py", line 58, in __init__
    self.build_graph()
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/db/migrations/loader.py", line 235, in build_graph
    self.applied_migrations = recorder.applied_migrations()
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/db/migrations/recorder.py", line 81, in applied_migrations
    if self.has_table():
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/db/migrations/recorder.py", line 57, in has_table
    with self.connection.cursor() as cursor:
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner
    return func(*args, **kwargs)
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/db/backends/base/base.py", line 323, in cursor
    return self._cursor()
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/db/backends/base/base.py", line 299, in _cursor
    self.ensure_connection()
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner
    return func(*args, **kwargs)
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/db/backends/base/base.py", line 281, in ensure_connection
    with self.wrap_database_errors:
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/db/utils.py", line 91, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/db/backends/base/base.py", line 282, in ensure_connection
    self.connect()
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner
    return func(*args, **kwargs)
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/db/backends/base/base.py", line 263, in connect
    self.connection = self.get_new_connection(conn_params)
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner
    return func(*args, **kwargs)
  File "/home/platec/production/venv/lib/python3.10/site-packages/django/db/backends/postgresql/base.py", line 215, in get_new_connection
    connection = Database.connect(**conn_params)
  File "/home/platec/production/venv/lib/python3.10/site-packages/psycopg2/__init__.py", line 122, in connect
    conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
django.db.utils.OperationalError: could not translate host name "db" to address: Temporary failure in name resolution

(venv) platec@platecbd:~/production$ 



Yes, I understand that.

And that’s the problem The DNS entry for “db” in the docker network created by the compose file is not available for anything not running in that docker network.

To access that database from outside the docker network that it is running in, you’ll need to find out what IP address is assigned to that PostgreSQL instance, and use that in your settings file. The name “db” has no meaning otherwise.

No, not good. Notice the error message received. The makemigrations command was unable to connect to the database.

Again, the name “db” is meaningless in your shell.