LoginSignup
17
12

More than 3 years have passed since last update.

djangoとpostgresqlをDockerで接続しようとしたときに「django.db.utils.OperationalError: could not translate host name "db" to address: Name or service not known」というエラーが出る

Posted at

エラー

Quickstart: Compose and Djangoを見ながらdockerでDjangoの開発環境を構築しようとして、docker-compose upしたときに以下のエラーが出た。

django.db.utils.OperationalError: could not translate host name "db" to address: Name or service not known

setting.py

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

修正前のdokcer-compose.yml

Docker-compose.yml
version: '3'

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

修正後のdocker-compose.yml

docker-compose.yml
version: '3'

services:
    web:
        build: .
        command: python3 manage.py runserver 0.0.0.0:8000
        volumes:
            - .:/code
        ports:
            - "8000:8000"
        depends_on:
            - db
    db:
        image: postgres
        ports: 
            - "5432"
        environment:
          - POSTGRES_DB=postgres
          - POSTGRES_USER=postgres
          - POSTGRES_PASSWORD=postgres

これで、エラーが解消しました。
Docker内でpostgresを使用するには、データベースユーザー、パスワード、db-nameなどの情報を構成する必要があります。これは、修正後のdokcer-compose.ymlにあるenvironmentにおいてコンテナの環境変数を設定することにより行うことができる。

17
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
12