docker-compose-patterns
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseDocker Compose Patterns
Docker Compose 模式
Overview
概述
This skill provides rules for creating, reviewing, and debugging Docker Compose configurations. Use it when the main artifact is or and the task is about service wiring rather than image-build internals.
compose.yamlcompose.override.yaml此技能提供创建、审查和调试 Docker Compose 配置的规则。当主要产物是 或 且任务涉及服务连接而非镜像构建内部细节时使用。
compose.yamlcompose.override.yamlWhen to use this skill
何时使用此技能
Activate this skill when:
- Creating a new for a project
compose.yaml - Adding or modifying services in an existing Compose file
- Setting up development overrides with
compose.override.yaml - Debugging service startup ordering or connectivity issues
在以下情况激活此技能:
- 为项目创建新的
compose.yaml - 在现有 Compose 文件中添加或修改服务
- 使用 设置开发环境覆盖
compose.override.yaml - 调试服务启动顺序或连接问题
Do not use this skill when
不要使用此技能的情况
Do not use this skill when:
- The project has no Docker setup yet and the main need is an initial scaffold
- The main task is writing or optimizing a
Dockerfile - The main task is improving build caching, image size, or runtime user configuration
在以下情况不要使用此技能:
- 项目尚无 Docker 设置,主要需求是初始脚手架
- 主要任务是编写或优化
Dockerfile - 主要任务是改进构建缓存、镜像大小或运行时用户配置
Core guidance
核心指导
File naming
文件命名
Use as the canonical filename. Do not use or — those are legacy names.
compose.yamldocker-compose.ymldocker-compose.yaml使用 作为规范文件名。不要使用 或 —— 这些是旧名称。
compose.yamldocker-compose.ymldocker-compose.yamlService definitions
服务定义
- Give services clear, lowercase names that reflect their role: ,
web,db,cache.worker - Always pin image tags to a specific version. Never use or omit the tag.
latest - Set for long-running infrastructure services and non-development deployments.
restart: unless-stopped - Add only when external tools need a predictable name. Otherwise, let Compose generate names.
container_name
- 为服务指定清晰的小写名称,反映其角色:、
web、db、cache。worker - 始终将镜像标签固定到特定版本。切勿使用 或省略标签。
latest - 对于长期运行的基础设施服务和非开发部署,设置 。
restart: unless-stopped - 仅在外部工具需要可预测名称时添加 。否则,让 Compose 生成名称。
container_name
Dependency modeling
依赖建模
- Use with
depends_onfor services that must be ready before dependents start.condition: service_healthy - Every service listed in with a health condition must have a
depends_ondefined.healthcheck - Do not rely on without conditions — it only guarantees container start, not readiness.
depends_on
- 对于必须在依赖方启动前就绪的服务,使用带 的
condition: service_healthy。depends_on - 每个带健康条件的 中列出的服务都必须定义
depends_on。healthcheck - 不要依赖没有条件的 —— 它只保证容器启动,不保证就绪。
depends_on
Health checks
健康检查
- Always add a to database services (Postgres, MySQL, Redis, MongoDB).
healthcheck - Use the service's native client tool for health checks when available (e.g., ,
pg_isready,redis-cli ping).mysqladmin ping - Set reasonable ,
interval,timeout, andretriesvalues. Start with:start_period,interval: 5s,timeout: 3s,retries: 3.start_period: 10s
- 始终为数据库服务(Postgres、MySQL、Redis、MongoDB)添加 。
healthcheck - 尽可能使用服务自带的客户端工具进行健康检查(例如 、
pg_isready、redis-cli ping)。mysqladmin ping - 设置合理的 、
interval、timeout和retries值。起始建议:start_period、interval: 5s、timeout: 3s、retries: 3。start_period: 10s
Health checks for distroless or scratch images
针对 distroless 或 scratch 镜像的健康检查
Distroless, scratch-based, and hardened images contain no shell, curl, or wget. Do not bake tools into these images — that defeats their purpose. Instead, use a healthcheck sidecar that shares the application's network namespace:
yaml
services:
api:
build:
context: .
target: runtime # distroless / hardened image
ports:
- "8080:8080"
# No healthcheck here — the image has no tools to run one
api-health:
image: curlimages/curl:8
network_mode: "service:api" # shares api's localhost
entrypoint: ["sleep", "infinity"] # keep sidecar alive for healthcheck
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8080/health"]
interval: 30s
timeout: 5s
retries: 3
start_period: 45s
deploy:
resources:
limits:
memory: 32MKey points:
- The sidecar must stay alive with so Compose can execute the healthcheck inside it.
entrypoint: ["sleep", "infinity"] - makes
network_mode: "service:api"inside the sidecar resolve to the api container's loopback — no extra networking needed.localhost - Keep the sidecar lightweight with a resource limit (32MB is sufficient for curl).
- Services that depend on being ready should reference the sidecar, not the api directly:
api
yaml
worker:
depends_on:
api-health:
condition: service_healthyDistroless、基于 scratch 和加固镜像不包含 shell、curl 或 wget。不要将工具嵌入这些镜像 —— 那会破坏其目的。相反,使用共享应用网络命名空间的 healthcheck 边车:
yaml
services:
api:
build:
context: .
target: runtime # distroless / hardened image
ports:
- "8080:8080"
# No healthcheck here — the image has no tools to run one
api-health:
image: curlimages/curl:8
network_mode: "service:api" # shares api's localhost
entrypoint: ["sleep", "infinity"] # keep sidecar alive for healthcheck
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8080/health"]
interval: 30s
timeout: 5s
retries: 3
start_period: 45s
deploy:
resources:
limits:
memory: 32M关键点:
- 边车必须通过 保持存活,以便 Compose 在其中执行健康检查。
entrypoint: ["sleep", "infinity"] - 使边车内的
network_mode: "service:api"解析为 api 容器的回环地址 —— 无需额外网络配置。localhost - 通过资源限制保持边车轻量(32MB 对 curl 足够)。
- 依赖 就绪的服务应引用 边车,而非直接引用 api:
api
yaml
worker:
depends_on:
api-health:
condition: service_healthyVolumes
卷
- Use named volumes for data that must persist across container recreations (database data, uploaded files).
- Use bind mounts only for development-time source code syncing.
- Define all named volumes in the top-level key.
volumes: - Do not mount the Docker socket unless the service genuinely requires it.
- 对需要跨容器重建持久化的数据(数据库数据、上传文件)使用命名卷。
- 仅对开发时的源代码同步使用绑定挂载。
- 在顶层 键中定义所有命名卷。
volumes: - 除非服务确实需要,否则不要挂载 Docker socket。
Networks
网络
- For single-application stacks, the default network is sufficient. Do not create custom networks unless you need isolation between service groups.
- When creating custom networks, prefer bridge driver and give networks descriptive names.
- Use the top-level key to define all custom networks.
networks:
- 对于单应用技术栈,默认网络足够。除非需要在服务组之间隔离,否则不要创建自定义网络。
- 创建自定义网络时,优先选择 bridge 驱动并为网络指定描述性名称。
- 使用顶层 键定义所有自定义网络。
networks:
Environment variables
环境变量
- Use for non-sensitive values that are few in number.
environment: - Use pointing to a
env_file:file for longer lists of variables..env - Never hardcode secrets (passwords, API keys) directly in . Use
compose.yamlor Docker secrets.env_file: - When defaults are needed in the block for local development, use variable substitution with fallbacks:
environment:. Never write bare plaintext values for password fields.${DB_PASSWORD:-postgres} - Add to
.env..gitignore
- 对于数量不多的非敏感值,使用 。
environment: - 对于较长的变量列表,使用指向 文件的
.env。env_file: - 切勿将机密(密码、API 密钥)直接硬编码在 中。使用
compose.yaml或 Docker secrets。env_file: - 当本地开发需要在 块中提供默认值时,使用带回退值的变量替换:
environment:。切勿为密码字段编写裸明文值。${DB_PASSWORD:-postgres} - 将 添加到
.env。.gitignore
Development overrides
开发覆盖
- Use for development-only settings. Compose loads it automatically alongside
compose.override.yaml.compose.yaml - Put bind mounts for source code, debug ports, and development environment variables in the override file.
- Use for file-syncing and auto-rebuild in development when supported.
develop.watch - Keep production-oriented settings in the base and override only what changes for development.
compose.yaml
- 仅对开发设置使用 。Compose 会自动将其与
compose.override.yaml一起加载。compose.yaml - 在覆盖文件中放置源代码的绑定挂载、调试端口和开发环境变量。
- 在支持时使用 进行开发中的文件同步和自动重建。
develop.watch - 将面向生产的设置保留在基础 中,仅覆盖开发所需更改的内容。
compose.yaml
Compose Watch
Compose Watch
- Prefer over manual bind mounts for development workflows.
develop.watch - Use for files that should be copied into the container on change (source code).
action: sync - Use for files that require a full image rebuild (dependency files like
action: rebuild,package.json).requirements.txt - Use for configuration files that need a process restart.
action: sync+restart
- 对于开发工作流,优先使用 而非手动绑定挂载。
develop.watch - 对更改时应复制到容器中的文件(源代码)使用 。
action: sync - 对需要完全重建镜像的文件(依赖文件如 、
package.json)使用requirements.txt。action: rebuild - 对需要进程重启的配置文件使用 。
action: sync+restart
Destructive commands
破坏性命令
Some Compose commands delete data irreversibly. Before running any of the following, state exactly which data will be deleted and get explicit confirmation from the user — do not run them as a side effect of debugging, restarting, or "cleaning up" a stack:
- /
docker compose down -v— deletes named volumes, including database data.docker compose down --volumes - /
docker volume rmrun against a Compose project's volumes — deletes volumes directly. For the standalone case (no Compose project in play), seedocker volume pruneinstead. A volume referenced viadocker-destructive-guardrailsisn't managed by the Compose project either (external: truewon't touch it) — treat it as the standalone case too: rundown -vwithoutdocker volume rmfirst, and get explicit confirmation before deleting it.-f - — deletes anonymous volumes attached to removed containers.
docker compose rm -v
If the goal is only to restart services or reclaim containers/networks, use (no ) or instead — these leave named volumes intact.
docker compose down-vdocker compose restart某些 Compose 命令会不可逆地删除数据。在运行以下任何命令之前,明确说明将删除哪些数据并获得用户的明确确认 —— 不要将其作为调试、重启或“清理”技术栈的副作用而运行:
- /
docker compose down -v—— 删除命名卷,包括数据库数据。docker compose down --volumes - /
docker volume rm针对 Compose 项目的卷运行 —— 直接删除卷。对于独立情况(不涉及 Compose 项目),请改用docker volume prune。通过docker-destructive-guardrails引用的卷也不由 Compose 项目管理(external: true不会触碰它)—— 也将其视为独立情况:先不带down -v运行-f,并在删除前获得明确确认。docker volume rm - —— 删除附加到已移除容器的匿名卷。
docker compose rm -v
如果目标只是重启服务或回收容器/网络,使用 (不加 )或 代替 —— 这些命令会保留命名卷。
docker compose down-vdocker compose restartRelated skills
相关技能
- For first-time Docker project scaffolding and baseline file creation, use .
docker-project-foundations - For Dockerfile internals, build caching, multi-stage builds, and , use
.dockerignore.docker-build-strategies - For destructive Docker CLI commands outside Compose (,
docker system prune, image/network/builder pruning, standalone volume deletion) and a cross-product index of destructive-command guardrails, usedocker rm -f.docker-destructive-guardrails
- 对于首次 Docker 项目脚手架和基线文件创建,使用 。
docker-project-foundations - 对于 Dockerfile 内部机制、构建缓存、多阶段构建和 ,使用
.dockerignore。docker-build-strategies - 对于 Compose 之外的破坏性 Docker CLI 命令(、
docker system prune、镜像/网络/构建器清理、独立卷删除)以及跨产品的破坏性命令防护索引,使用docker rm -f。docker-destructive-guardrails
References
参考
- — Detailed guidance on
references/service-dependencies.md, health check patterns for common databases, and startup ordering strategies.depends_on - — Patterns for volume mounts, named volumes, bind mounts, and network configuration.
references/volumes-and-networks.md
- —— 关于
references/service-dependencies.md、常见数据库健康检查模式以及启动顺序策略的详细指导。depends_on - —— 卷挂载、命名卷、绑定挂载和网络配置的模式。
references/volumes-and-networks.md
Assets
资源
- — Complete multi-service web app (app + Postgres + Redis) with health checks, dependencies, and named volumes.
assets/compose-web-app.yaml - — Development override showing bind mounts, debug ports, and Compose Watch configuration.
assets/compose-dev-override.yaml - — Before/after comparisons of common Compose mistakes and their fixes.
assets/bad-vs-good.md
- —— 完整的多服务 Web 应用(app + Postgres + Redis),包含健康检查、依赖和命名卷。
assets/compose-web-app.yaml - —— 展示绑定挂载、调试端口和 Compose Watch 配置的开发覆盖。
assets/compose-dev-override.yaml - —— 常见 Compose 错误及其修复的前后比较。
assets/bad-vs-good.md
Scripts
脚本
- — Validates
scripts/verify-compose.shwithcompose.yaml, without printing resolved configuration.docker compose config --quietExit status isbashbash scripts/verify-compose.sh [--help]when the Compose configuration is valid or help is requested, the non-zero status from0when validation fails, anddocker compose config --quietfor invalid arguments. Plain2can expose interpolated anddocker compose configcredentials in tool output or logs; use quiet validation by default. Compose warnings and errors are still emitted and may contain sensitive details.env_file
- — 使用
scripts/verify-compose.sh验证docker compose config --quiet,不打印解析后的配置。compose.yaml当 Compose 配置有效或请求帮助时退出状态为bashbash scripts/verify-compose.sh [--help],验证失败时返回0的非零状态,参数无效时返回docker compose config --quiet。普通的2可能会在工具输出或日志中暴露插值和docker compose config凭据;默认使用静默验证。Compose 警告和错误仍会输出,可能包含敏感细节。env_file
Checks
检查
- — Detailed verification runbook for manual review.
checks/verification.md
- — 用于手动审查的详细验证手册。
checks/verification.md