docker-compose-patterns
Use this skill when creating, modifying, or debugging Docker Compose configurations, even if the user just says they need to wire services together, add a database to their stack, or set up a local development environment with multiple containers. Covers service definitions, heal
Install
npx skills add https://github.com/docker/skills/tree/main/skills/docker-compose-patterns
claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install docker-skills@llmmart
git clone https://github.com/docker/skills.git
The skills CLI installs just this skill, for any of its supported agents. Claude Code installs the whole docker/skills collection as a plugin from our marketplace. Git is the plain clone.
Skill manifest
Docker Compose Patterns
Overview
This skill provides rules for creating, reviewing, and debugging Docker Compose configurations. Use it when the main artifact is compose.yaml or compose.override.yaml and the task is about service wiring rather than image-build internals.
When to use this skill
Activate this skill when:
- Creating a new
compose.yamlfor a project - Adding or modifying services in an existing Compose file
- Setting up development overrides with
compose.override.yaml - Debugging service startup ordering or connectivity issues
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
Core guidance
File naming
Use compose.yaml as the canonical filename. Do not use docker-compose.yml or docker-compose.yaml — those are legacy names.
Service definitions
- Give services clear, lowercase names that reflect their role:
web,db,cache,worker. - Always pin image tags to a specific version. Never use
latestor omit the tag. - Set
restart: unless-stoppedfor long-running infrastructure services and non-development deployments. - Add
container_nameonly when external tools need a predictable name. Otherwise, let Compose generate names.
Dependency modeling
- Use
depends_onwithcondition: service_healthyfor services that must be ready before dependents start. - Every service listed in
depends_onwith a health condition must have ahealthcheckdefined. - Do not rely on
depends_onwithout conditions — it only guarantees container start, not readiness.
Health checks
- Always add a
healthcheckto database services (Postgres, MySQL, Redis, MongoDB). - 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,retries, andstart_periodvalues. Start with:interval: 5s,timeout: 3s,retries: 3,start_period: 10s.
Health checks for distroless or scratch images
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:
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.22.0
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
Key points:
- The sidecar must stay alive with
entrypoint: ["sleep", "infinity"]so Compose can execute the healthcheck inside it. network_mode: "service:api"makeslocalhostinside the sidecar resolve to the api container's loopback — no extra networking needed.- Keep the sidecar lightweight with a resource limit (32MB is sufficient for curl).
- Services that depend on
apibeing ready should reference the sidecar, not the api directly:
worker:
depends_on:
api-health:
condition: service_healthy
Volumes
- 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
volumes:key. - Do not mount the Docker socket unless the service genuinely requires it.
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
networks:key to define all custom networks.
Environment variables
- Use
environment:for non-sensitive values that are few in number. - Use
env_file:pointing to a.envfile for longer lists of variables. - Never hardcode secrets (passwords, API keys) directly in
compose.yaml. Useenv_file:or Docker secrets. - When defaults are needed in the
environment:block for local development, use variable substitution with fallbacks:${DB_PASSWORD:-postgres}. Never write bare plaintext values for password fields. - Add
.envto.gitignore.
Development overrides
- Use
compose.override.yamlfor development-only settings. Compose loads it automatically alongsidecompose.yaml. - Put bind mounts for source code, debug ports, and development environment variables in the override file.
- Use
develop.watchfor file-syncing and auto-rebuild in development when supported. - Keep production-oriented settings in the base
compose.yamland override only what changes for development.
Compose Watch
- Prefer
develop.watchover manual bind mounts for development workflows. - Use
action: syncfor files that should be copied into the container on change (source code). - Use
action: rebuildfor files that require a full image rebuild (dependency files likepackage.json,requirements.txt). - Use
action: sync+restartfor configuration files that need a process 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/docker compose down --volumes— deletes named volumes, including database data.docker volume rm/docker volume prunerun against a Compose project's volumes — deletes volumes directly. For the standalone case (no Compose project in play), seedocker-destructive-guardrailsinstead. A volume referenced viaexternal: trueisn't managed by the Compose project either (down -vwon't touch it) — treat it as the standalone case too: rundocker volume rmwithout-ffirst, and get explicit confirmation before deleting it.docker compose rm -v— deletes anonymous volumes attached to removed containers.
If the goal is only to restart services or reclaim containers/networks, use docker compose down (no -v) or docker compose restart instead — these leave named volumes intact.
Related skills
- For first-time Docker project scaffolding and baseline file creation, use
docker-project-foundations. - For Dockerfile internals, build caching, multi-stage builds, and
.dockerignore, usedocker-build-strategies. - For destructive Docker CLI commands outside Compose (
docker system prune,docker rm -f, image/network/builder pruning, standalone volume deletion) and a cross-product index of destructive-command guardrails, usedocker-destructive-guardrails.
References
references/service-dependencies.md— Detailed guidance ondepends_on, health check patterns for common databases, and startup ordering strategies.references/volumes-and-networks.md— Patterns for volume mounts, named volumes, bind mounts, and network configuration.
Assets
assets/compose-web-app.yaml— Complete multi-service web app (app + Postgres + Redis) with health checks, dependencies, and named volumes.assets/compose-dev-override.yaml— Development override showing bind mounts, debug ports, and Compose Watch configuration.assets/bad-vs-good.md— Before/after comparisons of common Compose mistakes and their fixes.
Scripts
scripts/verify-compose.sh— Validates the Compose project in the current directory withdocker compose config --quiet, without printing resolved configuration. Run it from the project root (the directory that containscompose.yaml), with the script path resolved under this skill's directory:
Replacebash "<skill-dir>/scripts/verify-compose.sh" [--help]<skill-dir>with the absolute path of the folder that contains thisSKILL.md; thescripts/path is relative to that folder, not to the project. Do not change into the skill directory first: the script validates whatever Compose project is in the current directory. If the skill directory cannot be resolved, rundocker compose config --quietdirectly. Exit status is0when the Compose configuration is valid or help is requested, the non-zero status fromdocker compose config --quietwhen validation fails, and2for invalid arguments. Plaindocker compose configcan expose interpolated andenv_filecredentials in tool output or logs; use quiet validation by default. Compose warnings and errors are still emitted and may contain sensitive details.
Checks
checks/verification.md— Detailed verification runbook for manual review.
Files (skills)
-
agents
-
openai.yaml 261 B
interface: display_name: Docker Compose Patterns short_description: Patterns for robust, maintainable Docker Compose configurations. default_prompt: Use this skill when creating or modifying Docker Compose files. policy: allow_implicit_invocation: true
-
-
assets
-
bad-vs-good.md 2.8 KB
# Common Compose Mistakes: Before and After ## 1. Missing health checks on database dependencies ### Bad ```yaml services: web: build: . depends_on: - db db: image: postgres:17 ``` `depends_on` without a condition only waits for the container to start, not for Postgres to accept connections. The web service will crash on startup. ### Good ```yaml services: web: build: . depends_on: db: condition: service_healthy db: image: postgres:17 healthcheck: test: ["CMD-SHELL", "pg_isready -U postgres"] interval: 5s timeout: 3s retries: 3 start_period: 10s ``` --- ## 2. Using `latest` tag ### Bad ```yaml services: cache: image: redis:latest ``` `latest` is mutable. Builds become non-reproducible and can break without warning. ### Good ```yaml services: cache: image: redis:7 ``` Pin to a specific major or minor version. --- ## 3. Hardcoded secrets in compose.yaml ### Bad ```yaml services: db: image: postgres:17 environment: POSTGRES_PASSWORD: supersecretpassword123 ``` Secrets in the Compose file end up in version control. ### Good ```yaml services: db: image: postgres:17 env_file: - .env ``` With `.env` containing `POSTGRES_PASSWORD=supersecretpassword123` and `.env` listed in `.gitignore`. --- ## 4. Bind mount for database data ### Bad ```yaml services: db: image: postgres:17 volumes: - ./pgdata:/var/lib/postgresql/data ``` Bind mounts for database storage cause permission issues and poor I/O performance on macOS and Windows. ### Good ```yaml services: db: image: postgres:17 volumes: - db-data:/var/lib/postgresql/data volumes: db-data: ``` Named volumes are managed by Docker and perform correctly on all platforms. --- ## 5. Legacy filename ### Bad ``` docker-compose.yml ``` ### Good ``` compose.yaml ``` `compose.yaml` is the canonical filename. `docker-compose.yml` is legacy. --- ## 6. Development settings in the base Compose file ### Bad A single `compose.yaml` with bind mounts, debug ports, and development environment variables mixed in with production settings. ### Good Base `compose.yaml` with production-appropriate defaults. Development-only settings in `compose.override.yaml`, which Compose loads automatically: ```yaml # compose.override.yaml services: web: ports: - "9229:9229" environment: LOG_LEVEL: debug develop: watch: - action: sync path: ./src target: /app/src ``` --- ## 7. No restart policy ### Bad ```yaml services: web: image: myapp:1.0.0 ``` Without a restart policy, the container stays down after a crash or host reboot. ### Good ```yaml services: web: image: myapp:1.0.0 restart: unless-stopped ``` -
compose-dev-override.yaml 858 B
# Development override — loaded automatically as compose.override.yaml # Adds bind mounts, debug ports, and Compose Watch configuration # Usage: save as compose.override.yaml alongside compose.yaml services: web: build: context: . dockerfile: Dockerfile target: development ports: - "9229:9229" # Debugger port (8080 is already in the base file) environment: NODE_ENV: development LOG_LEVEL: debug develop: watch: - action: sync path: ./src target: /app/src - action: rebuild path: ./package.json - action: sync+restart path: ./config target: /app/config db: ports: - "127.0.0.1:5432:5432" # Expose DB only to local tools cache: ports: - "127.0.0.1:6379:6379" # Expose Redis only to local tools -
compose-web-app.yaml 1.1 KB
# Complete multi-service web application # Stack: Application + PostgreSQL + Redis # Run: docker compose up -d services: web: build: context: . dockerfile: Dockerfile ports: - "8080:8080" environment: DATABASE_URL: postgres://app:${POSTGRES_PASSWORD:-secret}@db:5432/myapp REDIS_URL: redis://cache:6379/0 depends_on: db: condition: service_healthy cache: condition: service_healthy restart: unless-stopped db: image: postgres:17 environment: POSTGRES_USER: app POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-secret} POSTGRES_DB: myapp volumes: - db-data:/var/lib/postgresql/data healthcheck: test: ["CMD-SHELL", "pg_isready -U app"] interval: 5s timeout: 3s retries: 3 start_period: 10s restart: unless-stopped cache: image: redis:7 volumes: - cache-data:/data healthcheck: test: ["CMD", "redis-cli", "ping"] interval: 5s timeout: 3s retries: 3 start_period: 5s restart: unless-stopped volumes: db-data: cache-data:
-
-
checks
-
verification.md 3.7 KB
# Verification Runbook for Generated Compose Files Run these checks against every generated `compose.yaml` before considering it complete. ## 1. Syntax and schema validation Run the bundled script from the project root (the directory that contains `compose.yaml`), with the script path resolved under the skill directory: ```bash bash "<skill-dir>/scripts/verify-compose.sh" [--help] ``` Replace `<skill-dir>` with the absolute path of this skill's directory, the folder that contains `SKILL.md` and this `checks/` folder. Do not change into the skill directory to run it; the script validates the Compose project in the current directory. Exit status is `0` when the Compose configuration is valid or help is requested, the non-zero status from `docker compose config --quiet` when validation fails, and `2` for invalid arguments. To run the underlying validation directly: ```bash docker compose config --quiet ``` This parses and validates the Compose file without printing the resolved configuration. It still resolves variables and reads service `env_file` files. If it exits non-zero, fix the reported errors before proceeding. Plain `docker compose config` renders interpolated and `env_file` credentials. Do not capture that output in CI logs or agent transcripts. If inspecting the rendered configuration is necessary, use a separate copy with dummy credentials and review it locally. `--quiet` suppresses the configuration dump, not warnings or errors; diagnostics may still contain sensitive details. ## 2. Health check presence Verify that every database, cache, or message broker service has a `healthcheck` defined. Review the Compose source files, including overrides, and confirm these services include `healthcheck.test`, `healthcheck.interval`, `healthcheck.timeout`, `healthcheck.retries`, and `healthcheck.start_period`. For rendered inspection, follow the dummy-credential precaution above. Services that must have health checks: - PostgreSQL, MySQL, MariaDB - Redis, Memcached - MongoDB - RabbitMQ, Kafka - Elasticsearch ## 3. Dependency ordering For every service with `depends_on`: - Confirm `condition: service_healthy` is set for infrastructure dependencies. - Confirm the referenced service has a matching `healthcheck`. - Confirm no circular dependencies exist (Compose will reject these, but verify intent). ## 4. Volume definitions - Every volume referenced in a service's `volumes:` list that uses the `name:/path` format must have a corresponding entry in the top-level `volumes:` key. - Database services must use named volumes, not bind mounts, for data directories. - Bind mounts should appear only in development override files. ## 5. Environment variables and secrets - No plaintext passwords, API keys, or tokens appear directly in `compose.yaml`. - Sensitive values use `env_file:` or Docker secrets. - If `.env` is referenced, confirm `.env` is in `.gitignore`. ## 6. Published ports and host mounts - Published datastore ports bind to loopback unless remote host access is explicitly required. - Services do not mount the Docker socket from `/var/run/docker.sock` or `/run/docker.sock`. ## 7. Image tags - No service uses the `latest` tag or omits the tag entirely. - All image references include an explicit version. ## 8. Runtime verification After `docker compose up -d`: ```bash # Check all services are running and healthy docker compose ps # Verify health check status specifically docker inspect --format='{{.State.Health.Status}}' <container_name> # Check logs for startup errors docker compose logs --tail=50 # Verify inter-service connectivity docker compose exec web ping -c 1 db ``` ## 9. File naming - The file is named `compose.yaml`, not `docker-compose.yml` or `docker-compose.yaml`. - Development overrides are in `compose.override.yaml`.
-
-
references
-
service-dependencies.md 2.8 KB
# Service Dependencies and Startup Ordering ## depends_on conditions The `depends_on` key supports three conditions: | Condition | Meaning | |---|---| | `condition: service_started` | Waits only for the container to start (default if no condition specified). | | `condition: service_healthy` | Waits for the container's health check to pass. | | `condition: service_completed_successfully` | Waits for the container to run and exit with code 0. Useful for init/migration containers. | Always use `condition: service_healthy` for infrastructure services (databases, caches, message brokers). The `service_started` condition is insufficient because a container can be running before the process inside is accepting connections. ## Health check patterns for common services ### PostgreSQL ```yaml healthcheck: test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-postgres}"] interval: 5s timeout: 3s retries: 3 start_period: 10s ``` ### MySQL / MariaDB ```yaml healthcheck: test: ["CMD", "mysqladmin", "ping", "-h", "localhost"] interval: 5s timeout: 3s retries: 3 start_period: 20s ``` MySQL can take longer to initialize on first run. Use a `start_period` of 20s or more. ### Redis ```yaml healthcheck: test: ["CMD", "redis-cli", "ping"] interval: 5s timeout: 3s retries: 3 start_period: 5s ``` ### MongoDB ```yaml healthcheck: test: ["CMD", "mongosh", "--eval", "db.adminCommand('ping')"] interval: 5s timeout: 3s retries: 3 start_period: 10s ``` ### RabbitMQ ```yaml healthcheck: test: ["CMD", "rabbitmq-diagnostics", "check_running"] interval: 10s timeout: 5s retries: 3 start_period: 30s ``` RabbitMQ has a longer startup time. Set `start_period` to at least 30s. ### Elasticsearch ```yaml healthcheck: test: ["CMD-SHELL", "curl -fs http://localhost:9200/_cluster/health || exit 1"] interval: 10s timeout: 5s retries: 5 start_period: 30s ``` ## Init containers pattern Use `service_completed_successfully` for one-shot tasks like database migrations: ```yaml services: migrate: image: myapp:1.2.0 command: ["./manage.py", "migrate"] depends_on: db: condition: service_healthy web: image: myapp:1.2.0 depends_on: db: condition: service_healthy migrate: condition: service_completed_successfully ``` This ensures migrations complete before the web service starts. ## Restart behavior and dependencies `depends_on` only governs initial startup ordering. It does not re-trigger if a dependency restarts. For runtime resilience: - Configure application-level retry/reconnect logic. - Use `restart: unless-stopped` so services recover from transient failures. - Do not chain long dependency trees. Keep the graph shallow — deep chains increase total startup time and fragility. -
volumes-and-networks.md 3.4 KB
# Volumes and Networks ## Volume types ### Named volumes Use named volumes for data that must persist across container recreations: ```yaml services: db: image: postgres:17 volumes: - db-data:/var/lib/postgresql/data volumes: db-data: ``` Named volumes are managed by Docker. They survive `docker compose down` (but not `docker compose down -v`, which deletes them and their data irreversibly). Never run `down -v` to work around a startup or connectivity problem — get explicit user confirmation first. ### Bind mounts Use bind mounts to sync host directories into containers. Appropriate for development-time source code mounting only: ```yaml services: web: build: . volumes: - ./src:/app/src ``` Do not use bind mounts for database data — they cause permission issues and poor performance on macOS and Windows. ### Anonymous volumes Avoid anonymous volumes (volumes with no name and no host path). They are hard to track and clean up. Always use named volumes. ### tmpfs mounts Use `tmpfs` for ephemeral scratch data that should not persist: ```yaml services: app: image: myapp:1.0.0 tmpfs: - /tmp - /app/cache ``` ## Volume mount flags - Use `:ro` to mount volumes as read-only when the container should not write to them. - Use `:cached` or `:delegated` on macOS only when performance requires it and data consistency tradeoffs are acceptable. Prefer Compose Watch (`develop.watch`) over bind mounts with performance flags. ## Volume patterns ### Excluding node_modules from bind mounts When bind-mounting a Node.js project, exclude `node_modules` with an anonymous volume to prevent host dependencies from overwriting container dependencies: ```yaml services: web: build: . volumes: - ./:/app - /app/node_modules ``` This mounts the project root but keeps the container's own `node_modules` intact. ### Sharing data between services Use a named volume to share files between services: ```yaml services: generator: image: myapp:1.0.0 volumes: - shared-data:/output consumer: image: nginx:1.27 volumes: - shared-data:/usr/share/nginx/html:ro volumes: shared-data: ``` ## Networks ### Default network Compose creates a default network for each project. All services join it automatically. Services can reach each other by service name as the hostname. For most single-application stacks, the default network is sufficient. ### Custom networks for isolation Use custom networks when you need to isolate groups of services: ```yaml services: web: image: myapp:1.0.0 networks: - frontend - backend db: image: postgres:17 networks: - backend proxy: image: nginx:1.27 networks: - frontend networks: frontend: backend: ``` In this example, `proxy` cannot reach `db` directly because they share no network. `web` bridges both. ### External networks Use `external: true` to reference a network created outside this Compose file: ```yaml networks: shared: external: true name: my-shared-network ``` This is useful when multiple Compose projects need to communicate. ### Network aliases Use aliases to give a service additional hostnames on a specific network: ```yaml services: db: image: postgres:17 networks: backend: aliases: - database - postgres ``` Other services on the `backend` network can reach this service as `db`, `database`, or `postgres`.
-
-
scripts
-
verify-compose.sh 672 B
#!/usr/bin/env bash # Verify Compose configuration. Run from the project root. # Usage: bash "<skill-dir>/scripts/verify-compose.sh" [--help] # <skill-dir> is the directory that contains this skill's SKILL.md. set -euo pipefail usage() { echo "Usage: bash \"<skill-dir>/scripts/verify-compose.sh\" [--help]" echo "Run from the project root; <skill-dir> is the directory that contains this skill's SKILL.md." echo "Validates compose.yaml with docker compose config --quiet (no rendered configuration)." } if [[ "${1:-}" == "--help" && $# == 1 ]]; then usage exit 0 fi if (( $# != 0 )); then usage >&2 exit 2 fi docker compose config --quiet
-
-
SKILL.md 9.5 KB
--- name: docker-compose-patterns description: Use this skill when creating, modifying, or debugging Docker Compose configurations, even if the user just says they need to wire services together, add a database to their stack, or set up a local development environment with multiple containers. Covers service definitions, health checks, dependency ordering, volumes, networks, environment variables, and development overrides. license: Apache-2.0 compatibility: Requires Docker Compose v2 (compose.yaml format). --- # Docker Compose Patterns ## Overview This skill provides rules for creating, reviewing, and debugging Docker Compose configurations. Use it when the main artifact is `compose.yaml` or `compose.override.yaml` and the task is about service wiring rather than image-build internals. ## When to use this skill Activate this skill when: - Creating a new `compose.yaml` for a project - Adding or modifying services in an existing Compose file - Setting up development overrides with `compose.override.yaml` - Debugging service startup ordering or connectivity issues ## 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 ## Core guidance ### File naming Use `compose.yaml` as the canonical filename. Do not use `docker-compose.yml` or `docker-compose.yaml` — those are legacy names. ### Service definitions - Give services clear, lowercase names that reflect their role: `web`, `db`, `cache`, `worker`. - Always pin image tags to a specific version. Never use `latest` or omit the tag. - Set `restart: unless-stopped` for long-running infrastructure services and non-development deployments. - Add `container_name` only when external tools need a predictable name. Otherwise, let Compose generate names. ### Dependency modeling - Use `depends_on` with `condition: service_healthy` for services that must be ready before dependents start. - Every service listed in `depends_on` with a health condition must have a `healthcheck` defined. - Do not rely on `depends_on` without conditions — it only guarantees container start, not readiness. ### Health checks - Always add a `healthcheck` to database services (Postgres, MySQL, Redis, MongoDB). - 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`, `retries`, and `start_period` values. Start with: `interval: 5s`, `timeout: 3s`, `retries: 3`, `start_period: 10s`. #### Health checks for distroless or scratch images 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.22.0 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 ``` Key points: - The sidecar must stay alive with `entrypoint: ["sleep", "infinity"]` so Compose can execute the healthcheck inside it. - `network_mode: "service:api"` makes `localhost` inside the sidecar resolve to the api container's loopback — no extra networking needed. - Keep the sidecar lightweight with a resource limit (32MB is sufficient for curl). - Services that depend on `api` being ready should reference the **sidecar**, not the api directly: ```yaml worker: depends_on: api-health: condition: service_healthy ``` ### Volumes - 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 `volumes:` key. - Do not mount the Docker socket unless the service genuinely requires it. ### 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 `networks:` key to define all custom networks. ### Environment variables - Use `environment:` for non-sensitive values that are few in number. - Use `env_file:` pointing to a `.env` file for longer lists of variables. - Never hardcode secrets (passwords, API keys) directly in `compose.yaml`. Use `env_file:` or Docker secrets. - When defaults are needed in the `environment:` block for local development, use variable substitution with fallbacks: `${DB_PASSWORD:-postgres}`. Never write bare plaintext values for password fields. - Add `.env` to `.gitignore`. ### Development overrides - Use `compose.override.yaml` for development-only settings. Compose loads it automatically alongside `compose.yaml`. - Put bind mounts for source code, debug ports, and development environment variables in the override file. - Use `develop.watch` for file-syncing and auto-rebuild in development when supported. - Keep production-oriented settings in the base `compose.yaml` and override only what changes for development. ### Compose Watch - Prefer `develop.watch` over manual bind mounts for development workflows. - Use `action: sync` for files that should be copied into the container on change (source code). - Use `action: rebuild` for files that require a full image rebuild (dependency files like `package.json`, `requirements.txt`). - Use `action: sync+restart` for configuration files that need a process 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` / `docker compose down --volumes` — deletes named volumes, including database data. - `docker volume rm` / `docker volume prune` run against a Compose project's volumes — deletes volumes directly. For the standalone case (no Compose project in play), see `docker-destructive-guardrails` instead. A volume referenced via `external: true` isn't managed by the Compose project either (`down -v` won't touch it) — treat it as the standalone case too: run `docker volume rm` without `-f` first, and get explicit confirmation before deleting it. - `docker compose rm -v` — deletes anonymous volumes attached to removed containers. If the goal is only to restart services or reclaim containers/networks, use `docker compose down` (no `-v`) or `docker compose restart` instead — these leave named volumes intact. ## Related skills - For first-time Docker project scaffolding and baseline file creation, use `docker-project-foundations`. - For Dockerfile internals, build caching, multi-stage builds, and `.dockerignore`, use `docker-build-strategies`. - For destructive Docker CLI commands outside Compose (`docker system prune`, `docker rm -f`, image/network/builder pruning, standalone volume deletion) and a cross-product index of destructive-command guardrails, use `docker-destructive-guardrails`. ## References - `references/service-dependencies.md` — Detailed guidance on `depends_on`, health check patterns for common databases, and startup ordering strategies. - `references/volumes-and-networks.md` — Patterns for volume mounts, named volumes, bind mounts, and network configuration. ## Assets - `assets/compose-web-app.yaml` — Complete multi-service web app (app + Postgres + Redis) with health checks, dependencies, and named volumes. - `assets/compose-dev-override.yaml` — Development override showing bind mounts, debug ports, and Compose Watch configuration. - `assets/bad-vs-good.md` — Before/after comparisons of common Compose mistakes and their fixes. ## Scripts - **`scripts/verify-compose.sh`** — Validates the Compose project in the current directory with `docker compose config --quiet`, without printing resolved configuration. Run it from the project root (the directory that contains `compose.yaml`), with the script path resolved under this skill's directory: ```bash bash "<skill-dir>/scripts/verify-compose.sh" [--help] ``` Replace `<skill-dir>` with the absolute path of the folder that contains this `SKILL.md`; the `scripts/` path is relative to that folder, not to the project. Do not change into the skill directory first: the script validates whatever Compose project is in the current directory. If the skill directory cannot be resolved, run `docker compose config --quiet` directly. Exit status is `0` when the Compose configuration is valid or help is requested, the non-zero status from `docker compose config --quiet` when validation fails, and `2` for invalid arguments. Plain `docker compose config` can expose interpolated and `env_file` credentials in tool output or logs; use quiet validation by default. Compose warnings and errors are still emitted and may contain sensitive details. ## Checks - `checks/verification.md` — Detailed verification runbook for manual review. -
skill.yaml 848 B
schema: v1 id: docker-compose-patterns version: 0.1.3 title: Docker Compose Patterns description: Patterns for robust, maintainable Docker Compose configurations. owns: - compose.yaml - compose.override.yaml - service-orchestration use_when: - The main artifact being created, edited, or reviewed is compose.yaml or compose.override.yaml. - The task involves service dependencies, readiness, health checks, networks, volumes, or overrides. - The user is debugging startup ordering or service-to-service connectivity in Compose. do_not_use_when: - The main task is creating the first Docker scaffold for a project with no existing setup. - The main task is optimizing how an image is built rather than how services are wired. delegates_to: - docker-project-foundations - docker-build-strategies - docker-destructive-guardrails
Comments (0)
Sign in to join the conversation.
Reviews (0)
No reviews yet.
No comments yet.