docker-compose-creator
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseDocker Compose Creator
Docker Compose 多容器应用设计与管理
Design and manage multi-container applications with Docker Compose for both development and production deployments.
使用Docker Compose设计并管理适用于开发和生产环境部署的多容器应用。
When to Use
适用场景
- Setting up local development environments
- Defining multi-service application stacks
- Managing service dependencies
- Configuring networking between services
- Environment variable management
- Production deployments (single host)
- Testing multi-service interactions
- 搭建本地开发环境
- 定义多服务应用栈
- 管理服务依赖
- 配置服务间网络
- 环境变量管理
- 生产环境部署(单主机)
- 测试多服务交互
Docker Compose Versions
Docker Compose 版本
| Version | Released | Features | Use Case |
|---|---|---|---|
| v3.x | 2016 | Service definitions, networks | Legacy (avoid for new projects) |
| v2.x | 2014 | Legacy format | Not recommended |
| v3.14 | 2023 | Full features, modern syntax | Current default |
Use version or later for new projects.
3.14| 版本 | 发布时间 | 特性 | 适用场景 |
|---|---|---|---|
| v3.x | 2016 | 服务定义、网络 | 旧版本(新项目避免使用) |
| v2.x | 2014 | 旧格式 | 不推荐使用 |
| v3.14 | 2023 | 全功能、现代语法 | 当前默认版本 |
新项目请使用或更高版本。
3.14Basic Structure
基本结构
yaml
version: '3.14'
services:
# Service definitions go here
volumes:
# Named volumes
networks:
# Custom networksyaml
version: '3.14'
services:
# Service definitions go here
volumes:
# Named volumes
networks:
# Custom networksFull-Featured Example: Web Application Stack
完整示例:Web应用栈
yaml
version: '3.14'
services:
# Frontend (Nginx)
nginx:
image: nginx:1.25-alpine
container_name: webapp-nginx
ports:
- "80:80"
- "443:443"
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf:ro
- ./ssl:/etc/nginx/ssl:ro
depends_on:
- api
networks:
- frontend
restart: unless-stopped
healthcheck:
test: ["CMD", "wget", "--quiet", "--tries=1", "--spider", "http://localhost/health"]
interval: 30s
timeout: 5s
retries: 3
start_period: 10s
# API Server (Node.js)
api:
build:
context: ./api
dockerfile: Dockerfile
target: production
container_name: webapp-api
environment:
- NODE_ENV=production
- DATABASE_HOST=postgres
- REDIS_HOST=redis
- LOG_LEVEL=info
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_started
networks:
- frontend
- backend
restart: unless-stopped
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
interval: 30s
timeout: 5s
retries: 3
start_period: 10s
logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "3"
# PostgreSQL Database
postgres:
image: postgres:15-alpine
container_name: webapp-db
environment:
- POSTGRES_DB=myapp
- POSTGRES_USER=appuser
- POSTGRES_PASSWORD=${DB_PASSWORD:?Database password required}
volumes:
- postgres_data:/var/lib/postgresql/data
- ./init-scripts:/docker-entrypoint-initdb.d:ro
networks:
- backend
restart: unless-stopped
healthcheck:
test: ["CMD-SHELL", "pg_isready -U appuser -d myapp"]
interval: 10s
timeout: 5s
retries: 5
start_period: 10s
logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "3"
# Redis Cache
redis:
image: redis:7-alpine
container_name: webapp-cache
command: redis-server --requirepass ${REDIS_PASSWORD:?Redis password required}
volumes:
- redis_data:/data
networks:
- backend
restart: unless-stopped
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 10s
timeout: 5s
retries: 5
# Background Worker (Optional)
worker:
build:
context: ./worker
dockerfile: Dockerfile
container_name: webapp-worker
environment:
- NODE_ENV=production
- DATABASE_HOST=postgres
- REDIS_HOST=redis
depends_on:
- postgres
- redis
networks:
- backend
restart: unless-stopped
volumes:
postgres_data:
redis_data:
networks:
frontend:
driver: bridge
backend:
driver: bridgeyaml
version: '3.14'
services:
# Frontend (Nginx)
nginx:
image: nginx:1.25-alpine
container_name: webapp-nginx
ports:
- "80:80"
- "443:443"
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf:ro
- ./ssl:/etc/nginx/ssl:ro
depends_on:
- api
networks:
- frontend
restart: unless-stopped
healthcheck:
test: ["CMD", "wget", "--quiet", "--tries=1", "--spider", "http://localhost/health"]
interval: 30s
timeout: 5s
retries: 3
start_period: 10s
# API Server (Node.js)
api:
build:
context: ./api
dockerfile: Dockerfile
target: production
container_name: webapp-api
environment:
- NODE_ENV=production
- DATABASE_HOST=postgres
- REDIS_HOST=redis
- LOG_LEVEL=info
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_started
networks:
- frontend
- backend
restart: unless-stopped
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
interval: 30s
timeout: 5s
retries: 3
start_period: 10s
logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "3"
# PostgreSQL Database
postgres:
image: postgres:15-alpine
container_name: webapp-db
environment:
- POSTGRES_DB=myapp
- POSTGRES_USER=appuser
- POSTGRES_PASSWORD=${DB_PASSWORD:?Database password required}
volumes:
- postgres_data:/var/lib/postgresql/data
- ./init-scripts:/docker-entrypoint-initdb.d:ro
networks:
- backend
restart: unless-stopped
healthcheck:
test: ["CMD-SHELL", "pg_isready -U appuser -d myapp"]
interval: 10s
timeout: 5s
retries: 5
start_period: 10s
logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "3"
# Redis Cache
redis:
image: redis:7-alpine
container_name: webapp-cache
command: redis-server --requirepass ${REDIS_PASSWORD:?Redis password required}
volumes:
- redis_data:/data
networks:
- backend
restart: unless-stopped
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 10s
timeout: 5s
retries: 5
# Background Worker (Optional)
worker:
build:
context: ./worker
dockerfile: Dockerfile
container_name: webapp-worker
environment:
- NODE_ENV=production
- DATABASE_HOST=postgres
- REDIS_HOST=redis
depends_on:
- postgres
- redis
networks:
- backend
restart: unless-stopped
volumes:
postgres_data:
redis_data:
networks:
frontend:
driver: bridge
backend:
driver: bridgeService Configuration
服务配置
Image vs Build
预构建镜像 vs 从Dockerfile构建
yaml
undefinedyaml
undefinedUsing pre-built image
Using pre-built image
services:
app:
image: myregistry/myapp:1.0.0
services:
app:
image: myregistry/myapp:1.0.0
Building from Dockerfile
Building from Dockerfile
services:
app:
build: ./app
services:
app:
build: ./app
Advanced build options
Advanced build options
services:
app:
build:
context: ./app
dockerfile: Dockerfile.prod
args:
- BUILD_ENV=production
target: production
undefinedservices:
app:
build:
context: ./app
dockerfile: Dockerfile.prod
args:
- BUILD_ENV=production
target: production
undefinedEnvironment Variables
环境变量
yaml
undefinedyaml
undefinedMethod 1: Inline
Method 1: Inline
services:
api:
environment:
- NODE_ENV=production
- LOG_LEVEL=info
services:
api:
environment:
- NODE_ENV=production
- LOG_LEVEL=info
Method 2: From file
Method 2: From file
services:
api:
env_file:
- .env
- .env.${ENVIRONMENT}
services:
api:
env_file:
- .env
- .env.${ENVIRONMENT}
Method 3: Mixed (with required variable check)
Method 3: Mixed (with required variable check)
services:
api:
environment:
- DATABASE_PASSWORD=${DB_PASSWORD:?Database password required}
- DATABASE_HOST=postgres
undefinedservices:
api:
environment:
- DATABASE_PASSWORD=${DB_PASSWORD:?Database password required}
- DATABASE_HOST=postgres
undefinedResource Limits
资源限制
yaml
services:
api:
# Memory: 512MB max, 256MB soft limit
mem_limit: 512m
memswap_limit: 1g
# CPU: 1 core
cpus: '1.0'
# File descriptor limit
ulimits:
nofile:
soft: 65536
hard: 65536yaml
services:
api:
# Memory: 512MB max, 256MB soft limit
mem_limit: 512m
memswap_limit: 1g
# CPU: 1 core
cpus: '1.0'
# File descriptor limit
ulimits:
nofile:
soft: 65536
hard: 65536Restart Policy
重启策略
yaml
services:
api:
restart: unless-stopped # Restart unless manually stopped
# Options: no, always, unless-stopped, on-failure
worker:
restart: on-failure
restart_policy:
condition: on-failure
delay: 5s
max_attempts: 3
window: 60syaml
services:
api:
restart: unless-stopped # Restart unless manually stopped
# Options: no, always, unless-stopped, on-failure
worker:
restart: on-failure
restart_policy:
condition: on-failure
delay: 5s
max_attempts: 3
window: 60sNetworking
网络配置
Service Discovery
服务发现
yaml
services:
api:
networks:
- backend
environment:
# Access postgres by service name on backend network
- DATABASE_HOST=postgres
postgres:
networks:
- backendyaml
services:
api:
networks:
- backend
environment:
# Access postgres by service name on backend network
- DATABASE_HOST=postgres
postgres:
networks:
- backendMulti-Network Setup
多网络配置
yaml
services:
api:
networks:
- frontend # Can talk to nginx
- backend # Can talk to postgres
nginx:
networks:
- frontend # Can talk to api
postgres:
networks:
- backend # Can talk to api, worker
networks:
frontend:
backend:yaml
services:
api:
networks:
- frontend # Can talk to nginx
- backend # Can talk to postgres
nginx:
networks:
- frontend # Can talk to api
postgres:
networks:
- backend # Can talk to api, worker
networks:
frontend:
backend:Port Mapping
端口映射
yaml
services:
api:
ports:
- "3000:3000" # Map container 3000 to host 3000
- "3001:3000" # Map container 3000 to host 3001
- "127.0.0.1:3000:3000" # Bind to localhost onlyyaml
services:
api:
ports:
- "3000:3000" # Map container 3000 to host 3000
- "3001:3000" # Map container 3000 to host 3001
- "127.0.0.1:3000:3000" # Bind to localhost onlyVolumes
数据卷
Named Volumes
命名数据卷
yaml
services:
postgres:
volumes:
- postgres_data:/var/lib/postgresql/data
volumes:
postgres_data:yaml
services:
postgres:
volumes:
- postgres_data:/var/lib/postgresql/data
volumes:
postgres_data:Bind Mounts
绑定挂载
yaml
services:
api:
volumes:
# Host path : Container path
- ./src:/app/src
# Read-only
- ./config:/app/config:ro
# With options
- ./logs:/app/logs:delegatedyaml
services:
api:
volumes:
# Host path : Container path
- ./src:/app/src
# Read-only
- ./config:/app/config:ro
# With options
- ./logs:/app/logs:delegatedTmpfs (Memory-backed)
Tmpfs(内存挂载)
yaml
services:
api:
tmpfs:
- /tmp
- /runyaml
services:
api:
tmpfs:
- /tmp
- /runDepends On
服务依赖
Basic Dependency
基础依赖
yaml
services:
api:
depends_on:
- postgres
- redis
postgres:
image: postgres:15
redis:
image: redis:7yaml
services:
api:
depends_on:
- postgres
- redis
postgres:
image: postgres:15
redis:
image: redis:7Conditional Dependency (Health Checks)
条件依赖(健康检查)
yaml
services:
api:
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_started
postgres:
healthcheck:
test: ["CMD-SHELL", "pg_isready -U user"]
interval: 10s
timeout: 5s
retries: 5yaml
services:
api:
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_started
postgres:
healthcheck:
test: ["CMD-SHELL", "pg_isready -U user"]
interval: 10s
timeout: 5s
retries: 5Health Checks
健康检查
yaml
services:
api:
healthcheck:
# Check command
test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
# Check interval
interval: 30s
# Timeout per check
timeout: 5s
# Retries before failure
retries: 3
# Wait before first check
start_period: 10syaml
services:
api:
healthcheck:
# Check command
test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
# Check interval
interval: 30s
# Timeout per check
timeout: 5s
# Retries before failure
retries: 3
# Wait before first check
start_period: 10sLogging
日志配置
yaml
services:
api:
logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "3"
labels: "service=api"
# Syslog
worker:
logging:
driver: "syslog"
options:
syslog-address: "udp://127.0.0.1:514"
tag: "{{.Name}}"yaml
services:
api:
logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "3"
labels: "service=api"
# Syslog
worker:
logging:
driver: "syslog"
options:
syslog-address: "udp://127.0.0.1:514"
tag: "{{.Name}}"Development vs Production
开发环境 vs 生产环境
Development (docker-compose.yml)
开发环境(docker-compose.yml)
yaml
version: '3.14'
services:
api:
build: ./api
ports:
- "3000:3000"
volumes:
- ./api/src:/app/src # Hot reload
environment:
- NODE_ENV=development
command: npm run devyaml
version: '3.14'
services:
api:
build: ./api
ports:
- "3000:3000"
volumes:
- ./api/src:/app/src # Hot reload
environment:
- NODE_ENV=development
command: npm run devProduction (docker-compose.prod.yml)
生产环境(docker-compose.prod.yml)
yaml
version: '3.14'
services:
api:
image: myregistry/myapp:1.0.0
restart: unless-stopped
environment:
- NODE_ENV=production
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
interval: 30s
timeout: 5s
retries: 3yaml
version: '3.14'
services:
api:
image: myregistry/myapp:1.0.0
restart: unless-stopped
environment:
- NODE_ENV=production
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
interval: 30s
timeout: 5s
retries: 3Running with Override
使用覆盖配置启动
bash
undefinedbash
undefinedDevelopment
Development
docker compose up
docker compose up
Production
Production
docker compose -f docker-compose.yml -f docker-compose.prod.yml up -d
undefineddocker compose -f docker-compose.yml -f docker-compose.prod.yml up -d
undefinedCommon Commands
常用命令
bash
undefinedbash
undefinedStart services
Start services
docker compose up
docker compose up
Start in background
Start in background
docker compose up -d
docker compose up -d
Stop services
Stop services
docker compose down
docker compose down
Stop without removing volumes
Stop without removing volumes
docker compose stop
docker compose stop
Remove containers, networks, volumes
Remove containers, networks, volumes
docker compose down -v
docker compose down -v
View logs
View logs
docker compose logs -f
docker compose logs -f
Specific service logs
Specific service logs
docker compose logs -f api
docker compose logs -f api
Execute command in service
Execute command in service
docker compose exec api npm test
docker compose exec api npm test
Run one-off command
Run one-off command
docker compose run api npm test
docker compose run api npm test
View service status
View service status
docker compose ps
docker compose ps
Rebuild images
Rebuild images
docker compose up --build
docker compose up --build
Remove and rebuild
Remove and rebuild
docker compose down --rmi all && docker compose up --build
undefineddocker compose down --rmi all && docker compose up --build
undefinedAdvanced Patterns
高级模式
Service Override
服务覆盖配置
yaml
undefinedyaml
undefineddocker-compose.override.yml (git-ignored)
docker-compose.override.yml (git-ignored)
services:
api:
volumes:
- ./src:/app/src # Local development
environment:
- DEBUG=true
undefinedservices:
api:
volumes:
- ./src:/app/src # Local development
environment:
- DEBUG=true
undefinedMultiple Configurations
多配置文件组合
bash
undefinedbash
undefinedProduction with monitoring
Production with monitoring
docker compose
-f docker-compose.yml
-f docker-compose.prod.yml
-f docker-compose.monitoring.yml
up -d
-f docker-compose.yml
-f docker-compose.prod.yml
-f docker-compose.monitoring.yml
up -d
undefineddocker compose
-f docker-compose.yml
-f docker-compose.prod.yml
-f docker-compose.monitoring.yml
up -d
-f docker-compose.yml
-f docker-compose.prod.yml
-f docker-compose.monitoring.yml
up -d
undefinedEnvironment-Specific Files
环境专属配置文件
bash
undefinedbash
undefinedLoad .env.${ENVIRONMENT}
Load .env.${ENVIRONMENT}
docker compose --env-file .env.production up -d
undefineddocker compose --env-file .env.production up -d
undefinedProduction Deployment Checklist
生产环境部署检查清单
- All services have healthchecks
- Services use
restart: unless-stopped - Sensitive data in (git-ignored)
.env - Volumes for persistent data
- Resource limits set
- Logging configured
- Networks isolated
- Use specific image tags (never )
latest - Test with
docker compose up -d && docker compose ps
- 所有服务配置健康检查
- 服务使用策略
restart: unless-stopped - 敏感数据存储在文件中(已加入git忽略)
.env - 使用数据卷存储持久化数据
- 设置资源限制
- 配置日志收集
- 网络隔离
- 使用特定镜像标签(绝不使用)
latest - 通过测试
docker compose up -d && docker compose ps
Troubleshooting
故障排查
bash
undefinedbash
undefinedCheck service status
Check service status
docker compose ps
docker compose ps
View detailed service info
View detailed service info
docker compose exec postgres psql -U user -c "\l"
docker compose exec postgres psql -U user -c "\l"
Network diagnosis
Network diagnosis
docker compose exec api ping postgres
docker compose exec api ping postgres
Resource usage
Resource usage
docker stats
docker stats
Rebuild and restart
Rebuild and restart
docker compose down --rmi local
docker compose up --build
undefineddocker compose down --rmi local
docker compose up --build
undefinedReferences
参考资料
- Docker Compose documentation: https://docs.docker.com/compose/
- Compose file format: https://docs.docker.com/compose/compose-file/
- Best practices: https://docs.docker.com/compose/production/
- Docker Compose官方文档:https://docs.docker.com/compose/
- Compose文件格式:https://docs.docker.com/compose/compose-file/
- 最佳实践:https://docs.docker.com/compose/production/