在 compose.yml 中可通过 labels 字段为服务或容器添加键值对标签,实现按业务、环境等维度分类管理,标签透传至容器并支持 docker ps 过滤及监控工具集成。

在 compose.yml(即 Docker Compose v2+ 的配置文件)中,可以通过 labels 字段为服务(service)或单个容器添加键值对标签,实现按业务、环境、团队、用途等维度分类管理容器。这些标签会透传到最终创建的容器上,配合 docker ps --filter label=... 或监控/编排工具(如 Portainer、Prometheus + cAdvisor)可高效筛选和分组。
在 service 级别配置 labels(最常用)
直接在服务定义下使用 labels,所有该服务启动的容器都会自动继承这些标签:
MiniMax 图片理解 + 网络搜索 MCP 工具。适配 Docker 环境(极空间等),支持图片 OCR 识别、图像内容理解、网络搜索。API Key 安全存储在本地 credentials 文件,不暴露在代码中。
services:
web:
image: nginx:alpine
labels:
- "com.example.team=frontend"
- "com.example.env=prod"
- "com.example.monitor=true"
- "org.opencontainers.image.source=https://git.example.com/app/web"
说明:
• 标签名建议用反向域名格式(如 com.example.xxx),避免命名冲突;
• 值支持字符串,含空格或特殊字符时用引号包裹;
• 多个标签可写成列表形式(如上),也可用映射语法(key-value):
labels:
com.example.team: "frontend"
com.example.env: "prod"
为特定部署实例添加差异化标签
若同一服务在不同环境中需不同标签(例如 dev/staging/prod),可结合 profiles 或环境变量动态控制:
- 用
profiles隔离配置:
services:
api:
image: myapp:latest
profiles: ["dev", "staging"]
labels:
- "com.example.env=${COMPOSE_ENV:-dev}"
- "com.example.tier=backend"
<p>api-prod:
extends: api
profiles: ["prod"]
labels:</p><ul><li>"com.example.env=prod"</li><li>"com.example.tier=backend"</li><li>"com.example.autoscale=enabled"
- 启动时通过
COMPOSE_ENV=staging docker compose --profile staging up即可生效。
labels 与容器生命周期管理联动
标签本身不改变行为,但可被外部工具识别并触发操作:
-
运维筛选:列出所有生产环境的前端服务容器
docker ps --filter label=com.example.env=prod --filter label=com.example.team=frontend -
自动清理:停用带临时标签的容器
docker rm $(docker ps -q --filter label=temporary=true) -
监控打标:Prometheus 的
cadvisor可通过--docker.label-container参数将 labels 作为指标标签暴露。
注意事项与最佳实践
• 不要将敏感信息(密码、token)写入 labels —— 它们在 docker inspect 中明文可见;
• 标签名尽量语义明确、层级清晰(如 org.company.department > department);
• 避免高频变更的字段(如请求量、状态)用 labels,应走 metrics 或 healthcheck;
• 若需运行时动态注入标签(如 Git SHA、部署时间),可用 env_file 或 CI 注入环境变量再引用。

















