
Docker Compose
- 11 installs
- 2 repo stars
- Updated July 29, 2026
- full-statck-skills/docker-skills
Write production docker-compose.yml files for multi-container apps, covering services, networks, volumes, secrets, health checks, and profiles.
About
Guides writing production-grade docker-compose.yml files for multi-container applications and service orchestration. A developer uses it when defining or modifying a Compose stack.
- Full Compose file syntax: services, networks, volumes, secrets, profiles, extends
- depends_on health checks, env strategies, override files, and kompose K8s migration
Docker Compose by the numbers
- 11 all-time installs (skills.sh)
- Ranked #993 of 1,435 DevOps & CI/CD skills by installs in the Skillselion catalog
- Data as of Jul 30, 2026 (Skillselion catalog sync)
npx skills add https://github.com/full-statck-skills/docker-skills --skill docker-composeAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 11 |
|---|---|
| repo stars | ★ 2 |
| Last updated | July 29, 2026 |
| Repository | full-statck-skills/docker-skills ↗ |
What it does
Write production docker-compose.yml files for multi-container apps, covering services, networks, volumes, secrets, health checks, and profiles.
Files
Docker Compose — 多容器编排与 Compose 文件
Expert guidance for writing production-grade Docker Compose configurations.
When to Use
ALWAYS use this skill when the user mentions:
- "docker compose", "docker-compose.yml", "compose 文件"
- "compose 怎么写", "compose 配置"
- "多容器", "multi-container", "服务编排"
- "depends_on", "profiles", "override"
- "compose network", "compose volume"
Complete File Structure
# compose.yml
name: myapp
services: # Container definitions
networks: # Network topology
volumes: # Persistent storage
secrets: # Sensitive data (Swarm)
configs: # Non-sensitive configs (Swarm)Services — Core Configuration
services:
web:
image: myapp:${TAG:-latest} # Pull from registry
# build: . # Or build from Dockerfile
# build: # Build with options
# context: .
# dockerfile: Dockerfile.prod
container_name: myapp-web # Explicit name (optional)
hostname: web
ports:
- "8080:8080" # host:container
- "127.0.0.1:8443:443" # bind to localhost
- "8080:8080/udp" # UDP
environment:
- NODE_ENV=production
- DB_HOST=db # Service name = hostname!
# env_file: .env.production # Load from file
volumes:
- app-logs:/var/log/app # Named volume
- ./config:/etc/app:ro # Bind mount (read-only)
- /tmp/app:/tmp # Bind mount (read-write)
depends_on:
db:
condition: service_healthy # Wait for health check
redis:
condition: service_started
healthcheck:
test: ["CMD", "wget", "-qO-", "http://localhost:8080/health"]
interval: 30s
timeout: 3s
retries: 3
start_period: 10s
restart: unless-stopped
deploy: # Swarm-only
replicas: 3
resources:
limits:
cpus: '0.5'
memory: 512M
profiles: # Optional service
- debugNetworking
Default Network (Auto-Created)
# Compose auto-creates a default bridge network.
# All services can reach each other by service name.
services:
web:
ports: ["8080:8080"]
db:
# No ports exposed externally — only accessible by 'web'Custom Networks
networks:
frontend: # Public-facing
backend:
internal: true # No external access
services:
web:
networks: [frontend, backend] # In both networks
db:
networks: [backend] # Backend only (isolated)
cache:
networks: [backend]Environment Variables
Approaches
| Method | Where | Best For |
|---|---|---|
environment: | In compose.yml | Simple, few vars |
env_file: | External .env.prod | Many vars, env-specific |
.env file | Project root (auto-loaded) | Default values, $VARIABLE substitution |
.env File (Auto-Loaded)
# .env — auto-loaded by docker compose
TAG=v1.2.3
DB_PASSWORD=secret123# compose.yml — uses ${TAG} and ${DB_PASSWORD}
services:
web:
image: myapp:${TAG:-latest}
db:
environment:
POSTGRES_PASSWORD: ${DB_PASSWORD}env_file
# .env.production
DB_HOST=prod-db.example.com
DB_PORT=5432services:
web:
env_file: .env.productionDepends On — Service Order
services:
db:
image: postgres:16-alpine
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 10s
retries: 5
web:
depends_on:
db:
condition: service_healthy # Wait for DB to be ready
redis:
condition: service_started # Wait for Redis to startProfiles — Optional Services
services:
app:
image: myapp
debug-tools:
image: nicolaka/netshoot
command: sleep infinity
profiles: [debug] # Only starts with --profile
elasticsearch:
image: elasticsearch:8.15.0
profiles: [analytics] # Only starts with --profiledocker compose --profile debug up # Starts app + debug-tools
docker compose --profile analytics up # Starts app + elasticsearchMulti-Environment with Override
compose.yml # Base configuration
compose.override.yml # Local dev overrides (auto-applied)
compose.prod.yml # Production overrides# Local: compose.yml + compose.override.yml (auto)
docker compose up -d
# Production: explicit files
docker compose -f compose.yml -f compose.prod.yml up -dMigration to Kubernetes
kompose convert -f compose.yml # Generates K8s YAML files
kubectl apply -f .Workflow — 推荐编排流程
Step 1: 规划服务: 列出所有服务、端口、数据卷、环境变量 Step 2: 编写 compose.yml: 定义 services/networks/volumes Step 3: 配置依赖: depends_on + condition: service_healthy Step 4: 本地验证: docker compose up -d → docker compose ps → docker compose logs Step 5: 生产部署: 添加 resource limits、restart policy、日志轮转 → docker compose -f compose.yml -f compose.prod.yml up -d
Gotchas — Common Pitfalls
- depends_on without healthcheck:
depends_ononly waits for container START, not READY. → Recovery: Always addcondition: service_healthy+healthcheck:block; usedocker compose psto verify health status. - Port conflict: Multiple services can't bind the same host port. → Recovery: Use different host ports or remove
ports:for internal-only services (they communicate via service name). - Bind mount paths: Relative paths are resolved from the compose file location. → Recovery: Use
./confignotconfig/; verify withdocker compose configto see resolved paths. - `.env` file security:
.envfiles often contain secrets. → Recovery: Add.envto.gitignore; use Docker secrets for Swarm; use.env.examplewith placeholder values. - `docker compose` vs `docker-compose`: Modern syntax is
docker compose(plugin). → Recovery:docker-compose(standalone binary) is deprecated; always usedocker compose(with space).
Boundary — 能力边界(适用与不适用场景)
| 分类 | 场景 | 说明 |
|---|---|---|
| ✅ 能做 | 多容器应用编排 | services/networks/volumes/secrets/configs 完整定义 |
| ✅ 能做 | 环境管理 | .env / env_file / override 文件策略 |
| ✅ 能做 | 依赖控制 | depends_on + healthcheck + profiles |
| ⚠️ 需条件 | 多主机部署 | 迁移到 Swarm(docker stack deploy)或 K8s |
| ⚠️ 需条件 | 滚动更新/自动扩缩 | Compose 不支持,需 Swarm 或 K8s |
| ❌ 超范围 | 编写 Dockerfile | 使用 docker-dockerfile |
| ❌ 超范围 | K8s 部署 | 使用 kompose convert + K8s 技能 |
| ❌ 超范围 | 云服务编排(Terraform) | IaaC 工具 |
When NOT to Use This Skill
| ❌ Skip | ✅ Use Instead |
|---|---|
| Single-container apps | docker-run |
| Writing Dockerfile | docker-dockerfile |
| Kubernetes deployment | K8s manifests / Helm charts |
| Docker basics | docker-basics |
Security & Stability
- Use
internal: truefor backend networks to prevent external access. - Never commit
.envfiles with secrets. Use CI secrets or Docker Swarm secrets. - Production Compose on single host: combine with systemd for auto-start on boot.
- Multi-host production: migrate to Swarm (
docker stack deploy) or Kubernetes.
📚 官方文档参考
| 文档 | 地址 |
|---|---|
| Docker Compose 概述 | https://docs.docker.com/compose/ |
| Compose 文件参考 | https://docs.docker.com/reference/compose-file/ |
| Compose CLI | https://docs.docker.com/reference/cli/docker/compose/ |
| 环境变量 | https://docs.docker.com/compose/environment-variables/ |
| Compose 网络 | https://docs.docker.com/compose/networking/ |
| 生产环境 Compose | https://docs.docker.com/compose/production/ |
🧭 Docker Skills Journey
📍 You are here: `docker-compose` — 多容器编排
← Previous: docker-buildx / docker-networking → Next: docker-production / docker-cicd
LAMP 全栈部署 — Nginx + PHP-FPM + MySQL + Redis
compose.yml
name: lamp-stack
services:
web:
image: nginx:1.27-alpine
ports:
- "8080:80"
volumes:
- ./app:/var/www/html:ro
- ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
- web_logs:/var/log/nginx
networks:
- frontend
depends_on:
php:
condition: service_healthy
restart: unless-stopped
healthcheck:
test: ["CMD", "wget", "-qO-", "http://localhost/health"]
interval: 30s
timeout: 3s
retries: 3
php:
build:
context: ./php
dockerfile: Dockerfile
volumes:
- ./app:/var/www/html:ro
networks:
- frontend
- backend
environment:
PHP_FPM_PM: dynamic
PHP_FPM_PM_MAX_CHILDREN: "10"
restart: unless-stopped
healthcheck:
test: ["CMD", "php-fpm-healthcheck"]
interval: 30s
timeout: 3s
retries: 3
db:
image: mysql:8.4
ports:
- "3306:3306"
volumes:
- db_data:/var/lib/mysql
- ./mysql/init.sql:/docker-entrypoint-initdb.d/init.sql:ro
networks:
- backend
environment:
MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
MYSQL_DATABASE: ${MYSQL_DATABASE}
MYSQL_USER: ${MYSQL_USER}
MYSQL_PASSWORD: ${MYSQL_PASSWORD}
restart: unless-stopped
healthcheck:
test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-u", "root", "-p${MYSQL_ROOT_PASSWORD}"]
interval: 10s
timeout: 5s
retries: 5
redis:
image: redis:7-alpine
ports:
- "6379:6379"
volumes:
- redis_data:/data
- ./redis/redis.conf:/usr/local/etc/redis/redis.conf:ro
networks:
- backend
command: redis-server /usr/local/etc/redis/redis.conf
restart: unless-stopped
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 10s
timeout: 3s
retries: 5
networks:
frontend:
driver: bridge
backend:
driver: bridge
internal: true
volumes:
db_data:
driver: local
redis_data:
driver: local
web_logs:
driver: local.env
MYSQL_ROOT_PASSWORD=rootpass123
MYSQL_DATABASE=myapp
MYSQL_USER=myuser
MYSQL_PASSWORD=mypass123启动
docker compose up -d
docker compose ps
docker compose logs -f
微服务编排 — API Gateway + 3 服务 + Kafka + DB
compose.yml
name: microservices
services:
gateway:
image: nginx:1.27-alpine
ports:
- "8080:80"
volumes:
- ./gateway/nginx.conf:/etc/nginx/nginx.conf:ro
networks:
- public
- internal
depends_on:
user-service:
condition: service_healthy
order-service:
condition: service_healthy
product-service:
condition: service_healthy
restart: unless-stopped
user-service:
build:
context: ./services/user
dockerfile: Dockerfile
networks:
- internal
environment:
DB_HOST: user-db
DB_PORT: "5432"
DB_NAME: users
DB_USER: ${DB_USER}
DB_PASSWORD: ${DB_PASSWORD}
KAFKA_BROKERS: kafka:9092
depends_on:
user-db:
condition: service_healthy
kafka:
condition: service_healthy
restart: unless-stopped
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8081/health"]
interval: 15s
timeout: 3s
retries: 3
deploy:
resources:
limits:
memory: 512M
cpus: "0.5"
user-db:
image: postgres:16-alpine
volumes:
- user_db_data:/var/lib/postgresql/data
networks:
- internal
environment:
POSTGRES_DB: users
POSTGRES_USER: ${DB_USER}
POSTGRES_PASSWORD: ${DB_PASSWORD}
restart: unless-stopped
healthcheck:
test: ["CMD-SHELL", "pg_isready -U ${DB_USER} -d users"]
interval: 10s
timeout: 5s
retries: 5
order-service:
build:
context: ./services/order
dockerfile: Dockerfile
networks:
- internal
environment:
DB_HOST: order-db
KAFKA_BROKERS: kafka:9092
depends_on:
order-db:
condition: service_healthy
kafka:
condition: service_healthy
restart: unless-stopped
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8082/health"]
interval: 15s
timeout: 3s
retries: 3
order-db:
image: mysql:8.4
volumes:
- order_db_data:/var/lib/mysql
networks:
- internal
environment:
MYSQL_ROOT_PASSWORD: ${DB_ROOT_PASSWORD}
MYSQL_DATABASE: orders
restart: unless-stopped
healthcheck:
test: ["CMD", "mysqladmin", "ping", "-h", "localhost"]
interval: 10s
timeout: 5s
retries: 5
product-service:
build:
context: ./services/product
dockerfile: Dockerfile
networks:
- internal
environment:
MONGO_HOST: product-db
KAFKA_BROKERS: kafka:9092
depends_on:
product-db:
condition: service_healthy
restart: unless-stopped
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8083/health"]
interval: 15s
timeout: 3s
retries: 3
product-db:
image: mongo:7
volumes:
- product_db_data:/data/db
networks:
- internal
restart: unless-stopped
healthcheck:
test: ["CMD", "mongosh", "--eval", "db.adminCommand('ping')"]
interval: 10s
timeout: 5s
retries: 5
kafka:
image: bitnami/kafka:3.7
networks:
- internal
environment:
KAFKA_CFG_NODE_ID: 0
KAFKA_CFG_PROCESS_ROLES: controller,broker
KAFKA_CFG_CONTROLLER_QUORUM_VOTERS: 0@kafka:9093
KAFKA_CFG_LISTENERS: PLAINTEXT://:9092,CONTROLLER://:9093
KAFKA_CFG_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092
KAFKA_CFG_LISTENER_SECURITY_PROTOCOL_MAP: CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT
KAFKA_CFG_CONTROLLER_LISTENER_NAMES: CONTROLLER
volumes:
- kafka_data:/bitnami/kafka
restart: unless-stopped
healthcheck:
test: ["CMD", "kafka-topics.sh", "--bootstrap-server", "localhost:9092", "--list"]
interval: 30s
timeout: 10s
retries: 5
networks:
public:
driver: bridge
internal:
driver: bridge
internal: true
volumes:
user_db_data:
order_db_data:
product_db_data:
kafka_data:启动策略
# 1. 先启动基础设施(DB + Kafka)
docker compose up -d user-db order-db product-db kafka
# 2. 等基础设施就绪后启动服务
docker compose up -d user-service order-service product-service
# 3. 最后启动网关
docker compose up -d gateway
监控栈 — Prometheus + Grafana + cAdvisor + Loki
compose.yml
name: monitoring
services:
prometheus:
image: prom/prometheus:v3.1.0
ports:
- "9090:9090"
volumes:
- ./prometheus/prometheus.yml:/etc/prometheus/prometheus.yml:ro
- prometheus_data:/prometheus
command:
- '--config.file=/etc/prometheus/prometheus.yml'
- '--storage.tsdb.path=/prometheus'
- '--storage.tsdb.retention.time=30d'
- '--web.enable-lifecycle'
networks:
- monitoring
restart: unless-stopped
grafana:
image: grafana/grafana:11.4.0
ports:
- "3000:3000"
volumes:
- grafana_data:/var/lib/grafana
- ./grafana/datasources:/etc/grafana/provisioning/datasources:ro
- ./grafana/dashboards:/etc/grafana/provisioning/dashboards:ro
environment:
GF_SECURITY_ADMIN_USER: ${GRAFANA_USER:-admin}
GF_SECURITY_ADMIN_PASSWORD: ${GRAFANA_PASSWORD:-admin}
GF_USERS_ALLOW_SIGN_UP: "false"
networks:
- monitoring
depends_on:
- prometheus
- loki
restart: unless-stopped
cadvisor:
image: gcr.io/cadvisor/cadvisor:v0.50.0
ports:
- "8080:8080"
volumes:
- /:/rootfs:ro
- /var/run:/var/run:ro
- /sys:/sys:ro
- /var/lib/docker/:/var/lib/docker:ro
- /dev/disk/:/dev/disk:ro
privileged: true
devices:
- /dev/kmsg
networks:
- monitoring
restart: unless-stopped
node-exporter:
image: prom/node-exporter:v1.8.2
ports:
- "9100:9100"
volumes:
- /proc:/host/proc:ro
- /sys:/host/sys:ro
- /:/rootfs:ro
command:
- '--path.procfs=/host/proc'
- '--path.sysfs=/host/sys'
- '--path.rootfs=/rootfs'
networks:
- monitoring
restart: unless-stopped
loki:
image: grafana/loki:3.2.0
ports:
- "3100:3100"
volumes:
- ./loki/loki-config.yaml:/etc/loki/local-config.yaml:ro
- loki_data:/loki
command: -config.file=/etc/loki/local-config.yaml
networks:
- monitoring
restart: unless-stopped
promtail:
image: grafana/promtail:3.2.0
volumes:
- /var/log:/var/log:ro
- /var/lib/docker/containers:/var/lib/docker/containers:ro
- ./promtail/promtail-config.yaml:/etc/promtail/config.yml:ro
command: -config.file=/etc/promtail/config.yml
networks:
- monitoring
depends_on:
- loki
restart: unless-stopped
alertmanager:
image: prom/alertmanager:v0.28.0
ports:
- "9093:9093"
volumes:
- ./alertmanager/alertmanager.yml:/etc/alertmanager/alertmanager.yml:ro
- alertmanager_data:/alertmanager
networks:
- monitoring
restart: unless-stopped
networks:
monitoring:
driver: bridge
volumes:
prometheus_data:
grafana_data:
loki_data:
alertmanager_data:prometheus/prometheus.yml
global:
scrape_interval: 15s
evaluation_interval: 15s
alerting:
alertmanagers:
- static_configs:
- targets: ['alertmanager:9093']
rule_files:
- '/etc/prometheus/alert.rules.yml'
scrape_configs:
- job_name: prometheus
static_configs:
- targets: ['localhost:9090']
- job_name: cadvisor
static_configs:
- targets: ['cadvisor:8080']
- job_name: node-exporter
static_configs:
- targets: ['node-exporter:9100']启动
docker compose up -d
# 访问
# Prometheus: http://localhost:9090
# Grafana: http://localhost:3000
# cAdvisor: http://localhost:8080
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Compose 文件完整语法速查
顶级元素
| 元素 | 说明 | 必需 |
|---|---|---|
name | 项目名称(v2.24+) | - |
services | 服务定义 | ✅ |
networks | 网络拓扑 | - |
volumes | 持久化卷 | - |
secrets | 敏感数据(仅 Swarm) | - |
configs | 非敏感配置(仅 Swarm) | - |
include | 引入其他 Compose 文件 | - |
Service 配置项速查
镜像与构建
services:
app:
image: nginx:1.27-alpine # 直接拉取
build: # 从 Dockerfile 构建
context: ./app
dockerfile: Dockerfile.prod
args:
NODE_ENV: production
target: production # 多阶段目标
platforms: # 多平台(BuildKit)
- linux/amd64
- linux/arm64
pull_policy: always # always/missing/never端口
ports:
- "8080:80" # host:container
- "127.0.0.1:3306:3306" # 仅本地
- "9090" # 随机 host 端口
- target: 80
published: 8080
protocol: tcp
mode: host # host/ingress (Swarm)环境变量
environment:
NODE_ENV: production
DB_URL: postgres://${DB_USER}:${DB_PASS}@db:5432/mydb
env_file:
- .env
- .env.production
# .env 文件(同目录下自动加载,用于变量替换 ${VAR})
# DB_USER=myuser
# DB_PASS=secret卷挂载
volumes:
- data_volume:/var/lib/mysql # 命名卷
- ./config:/etc/app/config:ro # bind mount(绝对/相对路径)
- /var/run/docker.sock:/var/run/docker.sock # Docker socket
- type: bind
source: ./logs
target: /var/log/app
- type: tmpfs
target: /tmp
tmpfs:
size: 128M依赖与启动顺序
depends_on:
db:
condition: service_healthy # service_started/service_healthy/service_completed_successfully
restart: true # 依赖重启时本服务也重启
redis:
condition: service_started
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8080/health"]
interval: 30s
timeout: 5s
retries: 3
start_period: 10s
start_interval: 2s资源限制(Compose v2.x / docker compose)
deploy:
resources:
limits:
cpus: "0.5"
memory: 256M
pids: 100
reservations:
cpus: "0.25"
memory: 128M重启策略
restart: unless-stopped # no/always/on-failure[:max-retries]/unless-stopped
deploy:
restart_policy:
condition: on-failure # none/on-failure/any
delay: 5s
max_attempts: 3
window: 120s其他常用
command: ["npm", "start"] # 覆盖 CMD
entrypoint: ["/custom-entrypoint.sh"] # 覆盖 ENTRYPOINT
user: "1000:1000" # 运行用户
working_dir: /app # 工作目录
stdin_open: true # -i
tty: true # -t
profiles: # 按 profile 启动
- debug
- tools
extra_hosts: # 额外 hosts
- "host.docker.internal:host-gateway"
dns:
- 8.8.8.8
- 1.1.1.1Networks
networks:
frontend:
driver: bridge
driver_opts:
com.docker.network.bridge.name: br-frontend
ipam:
config:
- subnet: 172.28.0.0/16
internal: false # 是否禁止外部访问
backend:
driver: bridge
internal: true # 仅内部互通
attachable: true # 允许外部容器连接Volumes
volumes:
db_data:
driver: local
driver_opts:
type: none
o: bind
device: /mnt/data/db
labels:
backup: daily
nfs_data:
driver: local
driver_opts:
type: nfs
o: addr=192.168.1.100,nolock,rw
device: ":/exports/data"Profiles(可选服务)
services:
app:
image: myapp
debug-tools:
image: nicolaka/netshoot
command: sleep infinity
profiles:
- debug # 仅 --profile debug 时启动docker compose --profile debug up -d片段复用(x-扩展)
x-logging: &default-logging
driver: json-file
options:
max-size: "10m"
max-file: "3"
x-healthcheck: &default-healthcheck
interval: 30s
timeout: 3s
retries: 3
services:
app1:
logging: *default-logging
healthcheck:
<<: *default-healthcheck
test: ["CMD", "curl", "-f", "http://localhost:8080/health"]
app2:
logging: *default-logging
healthcheck:
<<: *default-healthcheck
test: ["CMD", "curl", "-f", "http://localhost:8081/health"]include(模块化)
# compose.yml
include:
- path: ./infra/compose.db.yml
- path: ./infra/compose.mq.yml
- path: ./services/compose.api.yml
name: full-stack
Compose 环境变量管理策略
三种方式对比
| 方式 | 作用范围 | 优先级 | 典型场景 |
|---|---|---|---|
.env 文件 | $VAR 变量替换 | 自动加载 | 敏感值、环境差异 |
env_file | 容器内环境变量 | 低 | 大量共享变量 |
environment | 容器内环境变量 | 高 | 少量、明确的值 |
.env 文件(变量替换)
.env 放在 compose.yml 同目录,自动加载用于 ${VAR} 替换,不直接注入容器。
# .env
POSTGRES_VERSION=16
DB_USER=myapp
DB_PASSWORD=secret123services:
db:
image: postgres:${POSTGRES_VERSION:-16} # 替换为 16
environment:
POSTGRES_USER: ${DB_USER} # 替换为 myapp
POSTGRES_PASSWORD: ${DB_PASSWORD}| 语法 | 含义 |
|---|---|
${VAR} | 必需,无值则报错 |
${VAR:-default} | 有默认值 |
${VAR:?error} | 必需,无值则显示错误 |
${VAR:+alt} | 如果 VAR 有值则用 alt |
env_file(注入容器)
services:
app:
env_file:
- .env.common
- .env.api# .env.common
TZ=Asia/Shanghai
LOG_LEVEL=info
# .env.api
API_PORT=8080
RATE_LIMIT=100⚠️ env_file 不用于 $VAR 替换,如需替换请用 .env 或 cli --env-file。
environment(直接声明)
services:
app:
environment:
NODE_ENV: production
PORT: "8080"
DATABASE_URL: postgres://user:pass@db:5432/mydb多环境 override 策略
# compose.yml(基础配置)
services:
app:
image: myapp:latest
ports:
- "8080:8080"
environment:
LOG_LEVEL: info
# compose.override.yml(本地开发,默认自动合并)
services:
app:
build: .
ports:
- "8080:8080"
- "9229:9229" # debug port
environment:
NODE_ENV: development
LOG_LEVEL: debug
# compose.prod.yml(生产环境,-f 显式指定)
services:
app:
ports:
- "80:8080"
environment:
NODE_ENV: production
deploy:
resources:
limits:
memory: 512M
restart: always# 开发(自动合并 compose.yml + compose.override.yml)
docker compose up -d
# 生产(合并 compose.yml + compose.prod.yml)
docker compose -f compose.yml -f compose.prod.yml up -d优先级总结
命令行 -e VAR=val ← 最高
↓
compose.yml environment ← 中
↓
env_file 文件值 ← 低
↓
.env 文件默认值 ${VAR:-x} ← 最低最佳实践
| 场景 | 建议 |
|---|---|
| 密码/密钥 | .env 文件(不提交 Git) + Docker secrets(Swarm) |
| 环境差异 | override 文件:compose.dev.yml / compose.prod.yml |
| 共享配置 | env_file: .env.common |
| CI/CD | echo "$SECRET" > .env && docker compose up |
Compose 网络深度指南
默认网络行为
# compose.yml(不定义 networks)
services:
web:
image: nginx
api:
image: myapp启动后自动创建 <project>_default bridge 网络,所有服务加入,可通过 服务名 DNS 互访:
# web 容器中可 ping api 服务名
docker compose exec web ping api自定义网络
services:
web:
networks:
- frontend
api:
networks:
- frontend
- backend # 多网络
db:
networks:
- backend
networks:
frontend:
driver: bridge
backend:
driver: bridge
internal: true # 不暴露到宿主机网络模式选择
| 模式 | 说明 | 场景 |
|---|---|---|
bridge(默认) | 隔离网络 + NAT | 90% 场景 |
host | 共享宿主机网络栈 | 高性能/固定端口 |
none | 无网络 | 安全隔离 |
container:name | 共享另一容器网络 | sidecar 模式 |
services:
app:
network_mode: host
sidecar:
network_mode: service:app # 共享 app 的网络外部网络
连接已存在的 Docker 网络(如独立创建的共享网络):
docker network create shared-networkservices:
app:
networks:
- shared-network
networks:
shared-network:
external: true # 使用已存在的网络IP 地址分配
networks:
frontend:
driver: bridge
ipam:
config:
- subnet: 172.28.0.0/16
gateway: 172.28.0.1
services:
app:
networks:
frontend:
ipv4_address: 172.28.0.10DNS 解析
Compose 内置 DNS,服务名即域名:
服务名 → 该服务的所有容器 IP
<service>.<network> → 指定网络中的容器 IPservices:
api:
networks:
- frontend
- backend
web:
networks:
- frontend
# 可以访问: api, api.frontend, api.backend常见问题
| 问题 | 原因 | 解决 |
|---|---|---|
| 服务名无法解析 | 不同网络 | 加入同一自定义网络 |
localhost 不通 | Compose 中 localhost=本容器 | 用服务名 |
| 端口冲突 | host 网络直接占用 | 用 bridge + 端口映射 |
internal: true 仍可被宿主机访问 | 误解 | internal 仅禁止出站,非禁止入站映射 |
生产级 Compose 部署
资源限制
services:
api:
image: myapp:latest
deploy:
resources:
limits:
cpus: "1.0"
memory: 512M
pids: 100
reservations:
cpus: "0.5"
memory: 256M滚动更新(零停机)
services:
api:
image: myapp:latest
deploy:
replicas: 3
update_config:
parallelism: 1 # 每次更新几个
delay: 10s # 间隔
failure_action: rollback # 失败回滚
monitor: 30s # 监控新容器是否正常
max_failure_ratio: 0.3 # 容忍 30% 失败
order: start-first # 先启新再停旧
rollback_config:
parallelism: 1
delay: 0sSecrets 管理
secrets:
db_password:
file: ./secrets/db_password.txt
api_key:
external: true # Swarm 中已存在
services:
db:
secrets:
- db_password
environment:
MYSQL_PASSWORD_FILE: /run/secrets/db_passwordConfigs(非敏感配置)
configs:
nginx_conf:
file: ./nginx/nginx.conf
services:
web:
configs:
- source: nginx_conf
target: /etc/nginx/nginx.conf日志配置
services:
api:
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"
labels: "com.docker.compose.project,com.docker.compose.service"# 使用 loki 驱动
logging:
driver: loki
options:
loki-url: "http://loki:3100/loki/api/v1/push"
loki-retries: "5"
loki-batch-size: "400"systemd 守护
# /etc/systemd/system/myapp.service
[Unit]
Description=MyApp Docker Compose
Requires=docker.service
After=docker.service
[Service]
Type=oneshot
RemainAfterExit=yes
WorkingDirectory=/opt/myapp
ExecStart=/usr/bin/docker compose up -d
ExecStop=/usr/bin/docker compose down
ExecReload=/usr/bin/docker compose restart
TimeoutStartSec=0
[Install]
WantedBy=multi-user.targetsudo systemctl daemon-reload
sudo systemctl enable --now myappKompose:迁移到 Kubernetes
# 转换
kompose convert -f compose.yml -o k8s/
# 输出
# k8s/api-deployment.yaml
# k8s/api-service.yaml
# k8s/db-deployment.yaml
# k8s/db-service.yaml
# k8s/frontend-networkpolicy.yaml
# k8s/backend-networkpolicy.yaml
# 直接部署到 K8s
kompose up -f compose.ymlCompose vs Swarm vs K8s
| 特性 | Compose | Swarm | K8s |
|---|---|---|---|
| 单机 | ✅ | ✅ | ✅ |
| 多节点 | - | ✅ | ✅ |
| 自动扩缩 | - | ✅ | ✅ |
| 滚动更新 | - | ✅ | ✅ |
| 服务发现 | ✅(DNS) | ✅(内置) | ✅(kube-dns) |
| Secrets | ✅(文件) | ✅(加密) | ✅(etcd) |
| 学习曲线 | ⭐ | ⭐⭐ | ⭐⭐⭐⭐⭐ |