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

Hi team

I am docker rookie :frowning: and I need some help.

I am working in Ubunto 22.04.2 LTS, and I am having a project in Django and Python 3.10 running on Docker image.

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

The issue I have (and after searching on internet and reading a lot I was not able to fix) is that everytime 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.

Error message

(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

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

Django 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
}
"""

Hi Team,
any suggestion?

Thanks for the reminder. I saw the original post, but didn’t have time to reply or read the whole post then and forgot about it.

If you get temporary failure in name resolution, then it is either there is something wrong with Docker’s builtin DNS server to resolve service names, or the Python library is using an extenral DNS server directly which cannot resolve the name.

Please, share the output of the following commands to give us more info about the host and plugin versions

docker version
docker info

Remove anything private if it appears in the output like usernames or IP addresses.

You can also test the name resolution without Python. I usually use the nicolaka/nethsoot image. Connect to the same compose network and run “nslookup db” in the container.

Hi @rimelek, no worries at all, and thanks for replying to me.

Please see below the info about the command execution you requested:
thanks in advance for any comment here, if you need any further information, let me know.

Docker info:

(venv) platec@platecbd:~/production$ docker info
Client:
 Context:    default
 Debug Mode: false
 Plugins:
  app: Docker App (Docker Inc., v0.9.1-beta3)
  buildx: Docker Buildx (Docker Inc., v0.8.2-docker)
  compose: Docker Compose (Docker Inc., v2.16.0)
  scan: Docker Scan (Docker Inc., v0.23.0)

Server:
 Containers: 2
  Running: 2
  Paused: 0
  Stopped: 0
 Images: 5
 Server Version: 23.0.1
 Storage Driver: overlay2
  Backing Filesystem: extfs
  Supports d_type: true
  Using metacopy: false
  Native Overlay Diff: true
  userxattr: false
 Logging Driver: json-file
 Cgroup Driver: systemd
 Cgroup Version: 2
 Plugins:
  Volume: local
  Network: bridge host ipvlan macvlan null overlay
  Log: awslogs fluentd gcplogs gelf journald json-file local logentries splunk syslog
 Swarm: inactive
 Runtimes: io.containerd.runc.v2 runc
 Default Runtime: runc
 Init Binary: docker-init
 containerd version: 1e1ea6e986c6c86565bc33d52e34b81b3e2bc71f
 runc version: v1.1.4-0-g5fd4c4d
 init version: de40ad0
 Security Options:
  apparmor
  seccomp
   Profile: builtin
  cgroupns
 Kernel Version: 5.15.0-46-generic
 Operating System: Ubuntu 22.04.2 LTS
 OSType: linux
 Architecture: x86_64
 CPUs: 4
 Total Memory: 3.721GiB
 Name: platecbd
 ID: Y52U:L5AX:CVYT:ZUQY:7JY5:AGST:KZZH:NBXE:MHEC:H5SM:EK3D:QIFO
 Docker Root Dir: /var/lib/docker
 Debug Mode: false
 Registry: https://index.docker.io/v1/
 Labels:
 Experimental: false
 Insecure Registries:
  127.0.0.0/8
 Live Restore Enabled: false

(venv) platec@platecbd:~/production$ 


Docker version:

(venv) platec@platecbd:~/production$ docker version
Client: Docker Engine - Community
 Version:           20.10.17
 API version:       1.41
 Go version:        go1.17.11
 Git commit:        100c701
 Built:             Mon Jun  6 23:02:46 2022
 OS/Arch:           linux/amd64
 Context:           default
 Experimental:      true

Server: Docker Engine - Community
 Engine:
  Version:          23.0.1
  API version:      1.42 (minimum version 1.12)
  Go version:       go1.19.5
  Git commit:       bc3805a
  Built:            Thu Feb  9 19:47:01 2023
  OS/Arch:          linux/amd64
  Experimental:     false
 containerd:
  Version:          1.6.19
  GitCommit:        1e1ea6e986c6c86565bc33d52e34b81b3e2bc71f
 runc:
  Version:          1.1.4
  GitCommit:        v1.1.4-0-g5fd4c4d
 docker-init:
  Version:          0.19.0
  GitCommit:        de40ad0
(venv) platec@platecbd:~/production$ 

I also have the 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"]

and case it may be usefull docker-entrypoint:

#!/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 \
#    "$@"

It seems you are using 2-3 year old docker components, maybe it’s time to upgrade.

Althoigh @bluepuma77 is right about the time of upgrading, the old Docker should’t cause name resolution issues unless there was a bug in that specific version.

What I noticed on the other hand is that your client is older than your server.

which makes me wonder, how you installed Docker. How can the client have a different version?

Hav you tried the nicolaka/nethsoot container for debugging? Let us know if you need some help with connecting to the right network, but you just need to list the network names on the host using docker network ls and use the network name as a value of th --network option of docker run. Then you can try nslookup or ping to test name resolution