0

I create new project using Docker on Django. when I write settings to connect to Postgres it has some Error - (conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: could not translate host name "db" to address: nodename nor servname provided, or not known)

Thats my code in project : settings.py

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

docker-compose.yml

version: '3.7'
services:
  web:
    build: .
    command: python /code/manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - 8000:8000
    depends_on:

      - db


  db:

      image: postgres:11
      environment:
        POSTGRES_DB: "db"
        POSTGRES_HOST_AUTH_METHOD: "trust"

and Dockerfile:

# Pull base image
FROM python:3.7
# Set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
# Set work directory
WORKDIR /code
# Install dependencies

COPY Pipfile Pipfile.lock /code/
RUN pip install pipenv && pipenv install --system
# Copy project
COPY . /code/
RUN pip install psycopg2-binary

Please help to decide this problem.I read a lot information on stackoverflow about it.Changed code.But nothing to help me in this situation.

Luiba R
  • 1
  • 1
  • 2

1 Answers1

-1

You must specify the hostname in:

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

Otherwise it will try to connect to host with the name db.

steve
  • 5,870
  • 1
  • 21
  • 22