docker-composeでhealthcheckとdepends_onを組み合わせた確実な起動順序制御

Docker DevOps Database
結論

DBコンテナに healthcheck を定義し depends_on: { condition: service_healthy } で連動させます。

# 結論:docker-compose.yml 起動制御
version: '3.8'
services:
  db:
    image: postgres:16-alpine
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 5s
      timeout: 5s
      retries: 5

  app:
    build: .
    depends_on:
      db:
        condition: service_healthy

設定手順

  1. データベースコンテナ内にヘルスチェック用の診断コマンド(pg_isreadymysqladmin ping)を定義する
  2. interval, timeout, retries のヘルスチェックオプションを記述する
  3. アプリサービス側の depends_on を単純配列からオブジェクト形式にし condition: service_healthy を指定する