容器与云原生 / 系统课时
使用 Profiles
使用 Profiles
本课解决同一份 Compose 配置在开发、测试和运行环境中需要启动不同服务的问题。你将为调试与监控服务声明 Profile,并通过命令行参数或环境变量精确控制它们是否参与本次启动。
学习目标
- 为可选服务声明一个或多个 Profile
- 使用
--profile和COMPOSE_PROFILES激活服务 - 理解默认服务、显式目标服务与 Profile 之间的边界
声明默认服务与可选服务
未配置 profiles 的服务始终属于默认集合;配置了 profiles 的服务只有在对应 Profile 被激活时才会参与普通的 up。下面的配置让 Web 服务默认启动,而调试 Shell 和 Prometheus 按需启用。
services:
app:
image: nginx:1.27-alpine
ports:
- 8080:80
debug-shell:
image: alpine:3.20
profiles:
- debug
command: sh -c 'while true; do sleep 3600; done'
prometheus:
image: prom/prometheus:v2.55.1
profiles:
- monitoring这是一份可直接保存为 compose.yaml 的完整示例。配置生效后,app 不受 Profile 限制;debug-shell 只属于 debug,prometheus 只属于 monitoring。
验证默认启动范围
不指定 Profile 时,只启动没有 profiles 字段的服务。下面先后台启动项目,再输出当前运行中的服务名。
docker compose up -d >/dev/null
docker compose ps --services --status running预期输出
app如果之前启动过其他 Profile 服务,它们可能仍保持运行。为了得到干净的验证结果,可先执行 docker compose down,再重新运行示例。
激活单个 Profile
使用全局参数 --profile 激活本次命令需要的 Profile。它必须写在 compose 之后、子命令 up 之前。
docker compose --profile debug up -d >/dev/null
docker compose ps --services --status running预期输出
app
debug-shell服务显示顺序可能因 Compose 版本不同而变化,但结果中应同时包含 app 与 debug-shell,不应包含 prometheus。
同时激活多个 Profile
在脚本或 CI 中,可以通过 COMPOSE_PROFILES 传入逗号分隔的 Profile 列表。下面同时启用调试和监控服务。
COMPOSE_PROFILES=debug,monitoring docker compose up -d >/dev/null
docker compose ps --services --status running预期输出
app
debug-shell
prometheus也可以重复使用 --profile 参数达到相同效果。命令行参数只影响当前调用,环境变量则会影响当前 Shell 或流水线步骤中的后续 Compose 命令。
理解显式目标的边界
显式执行 docker compose up debug-shell 时,即使没有传入 --profile debug,目标服务仍可启动;但这不会自动启动同属 debug 的其他服务。Profile 控制的是普通模型选择范围,不应被当成完整的环境隔离机制。
若某个可选服务依赖默认服务,激活该 Profile 时 Compose 会按 depends_on 启动必要依赖。反过来,默认服务依赖一个未激活的可选服务会导致模型不一致,因此依赖方向应保持“可选服务依赖核心服务”。
使用建议
将应用、数据库等核心服务保留在默认集合,把调试面板、监控采集器、数据初始化器和本地辅助工具放入 Profile。Profile 名称应表达用途,如 debug、monitoring、tools,不要直接混用模糊的机器名或个人名。
本课总结
- 没有
profiles的服务默认参与启动,声明 Profile 的服务按需加入 --profile适合临时操作,COMPOSE_PROFILES适合脚本和 CI- 显式指定服务可以绕过其 Profile,但不会自动启用同 Profile 的全部服务
下一课预告
下一课将把 Compose 编排知识串联起来,形成可重复执行的启动、验证与排障流程。