用 Compose profiles 管理選用服務
同一份 compose 檔,開發時多跑幾個輔助容器,正式環境只跑核心服務。profiles 讓你用一個旗標切換。
常見需求:開發時想順便跑 Adminer、MailHog 這類輔助工具,但正式環境不要它們。與其維護兩份 compose 檔,用 profiles 把選用服務標起來。
基本用法
services:
app:
image: myapp
# 沒有 profiles,永遠會啟動
db:
image: postgres:16
# 核心服務,也永遠啟動
adminer:
image: adminer
profiles: [dev] # 只在 dev profile 啟動
mailhog:
image: mailhog/mailhog
profiles: [dev]
啟動
docker compose up -d # 只跑 app + db
docker compose --profile dev up -d # app + db + adminer + mailhog
沒有指定 profile 的服務一律啟動;標了 profile 的,只有該 profile 被啟用時才跑。
多個 profile
一個服務可以屬於多個 profile,也可以一次啟用多個:
debug-tools:
image: nicolaka/netshoot
profiles: [dev, debug]
docker compose --profile dev --profile debug up -d
用環境變數預設啟用
export COMPOSE_PROFILES=dev
docker compose up -d # 自動帶入 dev profile
放進 .env 檔也可以,團隊成員 clone 下來就有一致的開發設定。
注意相依性
如果一個「永遠啟動」的服務 depends_on 一個「有 profile」的服務,那個被依賴的服務也會被一起拉起來,即使 profile 沒啟用。設計相依關係時留意這點。
適用場景
- 開發輔助工具(DB 管理介面、假 SMTP、除錯容器)。
- 選用的功能模組(例如某個只有部分部署需要的 worker)。
- 一次性的工具容器(遷移、種子資料)——也可以用獨立的 profile 控制。
一份 compose 檔走天下,比維護 docker-compose.dev.yml、docker-compose.prod.yml 一堆覆寫檔清爽。