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
設定手順
- データベースコンテナ内にヘルスチェック用の診断コマンド(
pg_isreadyやmysqladmin ping)を定義する interval,timeout,retriesのヘルスチェックオプションを記述する- アプリサービス側の
depends_onを単純配列からオブジェクト形式にしcondition: service_healthyを指定する