在 Compose 中使用配置檔案
compose.yml
檔案中,並且僅在需要時啟用。將配置檔案分配給服務
服務透過 profiles
屬性 與配置檔案關聯,該屬性接受配置檔名稱的陣列。
services:
frontend:
image: frontend
profiles: [frontend]
phpmyadmin:
image: phpmyadmin
depends_on: [db]
profiles: [debug]
backend:
image: backend
db:
image: mysql
此處,服務 frontend
和 phpmyadmin
分別分配給配置檔案 frontend
和 debug
,因此只有在啟用其各自配置檔案時才會啟動。
沒有 profiles
屬性的服務始終處於啟用狀態。在這種情況下,執行 docker compose up
僅會啟動 backend
和 db
。
有效的配置檔名稱遵循 [a-zA-Z0-9][a-zA-Z0-9_.-]+
的正則表示式格式。
提示
應用程式的核心服務不應該分配
profiles
,這樣它們始終處於啟用狀態並自動啟動。
啟動特定配置檔案
要啟動特定配置檔案,請提供 --profile
命令列選項 或使用 COMPOSE_PROFILES
環境變數
$ docker compose --profile debug up
$ COMPOSE_PROFILES=debug docker compose up
以上命令都會啟動應用程式並啟用 debug
配置檔案。在上面的 compose.yml
檔案示例中,這會啟動服務 backend
、db
和 phpmyadmin
。
啟動多個配置檔案
你還可以啟用多個配置檔案,例如,使用 docker compose --profile frontend --profile debug up
,配置檔案 frontend
和 debug
將被啟用。
可以透過傳遞多個 --profile
標誌或為 COMPOSE_PROFILES
環境變數傳遞逗號分隔的列表來指定多個配置檔案。
$ docker compose --profile frontend --profile debug up
$ COMPOSE_PROFILES=frontend,debug docker compose up
如果你想同時啟用所有配置檔案,可以執行 docker compose --profile "*"
。
自動啟動配置檔案和依賴關係解析
當命令列上顯式指定了分配了 profiles
的服務時,其配置檔案會自動啟動,因此你無需手動啟動它們。這可以用於一次性服務和除錯工具。例如,考慮以下配置
services:
backend:
image: backend
db:
image: mysql
db-migrations:
image: backend
command: myapp migrate
depends_on:
- db
profiles:
- tools
# Only start backend and db
$ docker compose up -d
# This runs db-migrations (and,if necessary, start db)
# by implicitly enabling the profiles `tools`
$ docker compose run db-migrations
但請記住,docker compose
僅會自動啟動命令列上服務的配置檔案,而不會啟動任何依賴項的配置檔案。
這意味著目標服務 depends_on
的任何其他服務都應該:
- 共享一個通用配置檔案
- 始終啟動,透過省略
profiles
或顯式啟動匹配的配置檔案
services:
web:
image: web
mock-backend:
image: backend
profiles: ["dev"]
depends_on:
- db
db:
image: mysql
profiles: ["dev"]
phpmyadmin:
image: phpmyadmin
profiles: ["debug"]
depends_on:
- db
# Only start "web"
$ docker compose up -d
# Start mock-backend (and, if necessary, db)
# by implicitly enabling profiles `dev`
$ docker compose up -d mock-backend
# This fails because profiles "dev" is not enabled
$ docker compose up phpmyadmin
雖然定位 phpmyadmin
會自動啟動配置檔案 debug
,但它不會自動啟動 db
所需的配置檔案,即 dev
。
要解決這個問題,你需要將 debug
配置檔案新增到 db
服務中:
db:
image: mysql
profiles: ["debug", "dev"]
或者顯式啟動 dev
配置檔案:
# Profiles "debug" is started automatically by targeting phpmyadmin
$ docker compose --profile dev up phpmyadmin
$ COMPOSE_PROFILES=dev docker compose up phpmyadmin