1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Django+Postgresqlをdockerで環境構築したらDBに接続できなかった

Posted at

起きたこと

Django+PostgreSQLの開発環境をDockerで作ろうとしていたら,Django側で以下のエラーが出た.

2023-10-13 15:03:01 django.db.utils.OperationalError: connection to server at "db" (172.30.0.2), port 5432 failed: Connection refused
2023-10-13 15:03:01     Is the server running on that host and accepting TCP/IP connections?

構築は以下の記事を参考にした.

docker-compose.ymlはこんな感じ.

version: "3"
services:
  db:
    image: postgres:16.0
    env_file: .env
    ports:
      - "54320:5432"
  web:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    env_file: .env
    volumes:
      - ./src:/src
    ports:
      - "8000:8000"
    depends_on:
    - db

解決方法

クライアントツールを使ってホスト側から接続すると,接続できた.

psql -U postgres --port=54320 -h localhost

PostgreSQLが立ち上がる前にDjangoがDBに接続しようとしてて,それが原因で落ちていたらしい.
(教えてくれた友達ありがとう)

docker-compose.ymlにヘルスチェックを追加して次のように書き直したらうまく起動した.

version: "3"
services:
  db:
    image: postgres:16.0
    env_file: .env
    ports:
      - "54320:5432"
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 5s
      timeout: 5s
      retries: 5
  web:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    env_file: .env
    volumes:
      - ./src:/src
    ports:
      - "8000:8000"
    depends_on:
      db:
        condition: service_healthy
1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?