若要在一個 docker-compose 中起容器,達成「僅開啟特定容器」的效果時,可以透過 profiles 來達成。這邊筆記一下寫法和注意事項。
內容
1. 在每一個服務中,利用 profiles 的文字陣列來達成,像是 [‘dev’, ‘prod’] 就代表你下的 docker-compose up 需要包含這兩個關鍵字的其中一個,才會啟動。
2. 若你的容器服務沒有 profiles 變數,那就代表「都會啟動」
3. 有重複的字樣,可以透過 x-properties 來宣告並插入指定位置。請注意它沒有合併功能。
4. 可以透過 docker-compose config 來確認最後輸出的結果
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
version: "3.9" | |
name: "demo" | |
x-common-build: &common-build | |
context: "../" | |
dockerfile: "${PWD}/Dockerfile" | |
x-restart: &restart | |
restart: on-failure | |
services: | |
demo-dev: | |
container_name: demo-dev | |
profiles: ["dev"] | |
build: | |
<<: *common-build | |
args: # inject variables like {VITE_APP_BASE_API} from gitlab-ci | |
- VITE_APP_ENV_NAME=build-dev | |
- VITE_APP_BASE_API=https://jsonplaceholder.typicode.com | |
ports: | |
- "3000:80" | |
<<: *restart | |
demo-staging: | |
container_name: demo-staging | |
profiles: ["staging"] | |
build: | |
context: "../" | |
dockerfile: "${PWD}/Dockerfile" | |
args: # inject variables like {VITE_APP_BASE_API} from gitlab-ci | |
- VITE_APP_ENV_NAME=staging | |
- VITE_APP_BASE_API=https://jsonplaceholder.typicode.com | |
ports: | |
- "3001:80" | |
<<: *restart | |
demo-production: | |
container_name: demo-production | |
profiles: ["production"] | |
build: | |
<<: *common-build | |
args: # inject variables like {VITE_APP_BASE_API} from gitlab-ci | |
- VITE_APP_ENV_NAME=production | |
- VITE_APP_BASE_API=https://jsonplaceholder.typicode.com | |
ports: | |
- "3002:80" | |
<<: *restart |
參考資料
1. docker-compose up for only certain containers
2. YAML anchors
3. Docker Tip #82: Using YAML Anchors and X Properties in Docker Compose