bigywater.tech
Docker · 64

Compose profiles:按场景启动不同服务

想把调试工具、迁移任务这类服务放进同一个 compose 文件,却不想默认启动?profiles 就是干这个的。这篇逐项实测哪些命令会激活它、依赖带 profile 的服务会怎样,以及一个容易留下残留容器的 down 陷阱。

3 个服务
--profile debug 才会一起启动的服务数(默认只有 app 1 个)
invalid compose project
没有 profile 的服务依赖带 profile 的服务、又没激活它时的报错
down 之后还剩 2 个
不带 profile 的 docker compose down 停不掉带 profile 的 debug 和 tools

激活方式

实测 · 本机执行输出
  docker compose config --services:app
  docker compose --profile debug config --services:app debug tools
  docker compose up -d 之后在运行的服务:['app']
  --profile tools up -d:['app', 'tools']
  --profile debug up -d:['app', 'debug', 'tools'](tools 同时属于 tools 和 debug 两个 profile)
  环境变量 COMPOSE_PROFILES=tools,up -d:['app', 'tools']

--profile 参数或环境变量 COMPOSE_PROFILES;一个服务可以属于多个 profile,任意一个被激活就会启动。

点名

实测 · 本机执行输出
  docker compose up -d debug(没有 --profile):退出码 0;在运行的服务:['debug']
  run 之后留下的容器:[]
  docker compose run --rm tools echo …(没有 --profile):退出码 0;输出:hello-from-tools

直接 up 或 run 某个带 profile 的服务不需要 --profile,点名本身就激活了它。

依赖

实测 · 本机执行输出
  app depends_on debug,不加 profile:退出码 1;输出:service "app" depends on undefined service "debug": invalid compose project;在运行的服务:[]
  加 --profile debug:退出码 0;在运行的服务:['app', 'debug', 'tools']

没有 profile 的服务不能依赖带 profile 的服务,除非同时激活那个 profile,否则 compose 直接报「依赖了未定义的服务」。

清理

实测 · 本机执行输出
  --profile "*" up -d:['app', 'debug', 'tools']
  不带 profile 的 docker compose down 之后剩下的:['debug', 'tools']
  --profile "*" down 之后:[]

不带 profile 的 docker compose down 只处理当前激活的服务,带 profile 的容器会留下来。清理要加 --profile "*"。

分步演示

compose profiles
本步的对象

    本文用到的工具与边界

    • 本机 macOS 27 arm64 / Docker Desktop(Engine 29.8.2,容器跑在 Docker Desktop 自带的 Linux 虚拟机里,内核与宿主机的 macOS 不同);镜像为 linux/arm64;需要看虚拟机内部时用特权容器 + nsenter;计时用 time / date +%s%N,数字每次运行会有小幅抖动。Docker Compose v5.5.1;服务都是 alpine:3.20 sleep 120;运行状态取自 docker ps 的容器名;compose 项目名 bwlab-c59,实验后已用 --profile "*" down -v 清理
    • 没有验证:depends_on 的 required: false 对 profile 服务的效果、profiles 与 extends / include 的交互、COMPOSE_PROFILES 写多个值的分隔方式(逗号)、docker compose ps 默认是否列出未激活的容器
    京ICP备2026067502号-1京公网安备11010502063487号