服务扩缩容
Docker Compose 允许你轻松扩展服务实例数量。
单机环境扩缩容
扩展服务
sh
# 将 web 服务扩展到 3 个实例
docker compose up -d --scale web=3查看运行实例
sh
docker compose ps缩减服务
sh
# 将 web 服务缩减到 1 个实例
docker compose up -d --scale web=1Swarm 模式扩缩容
在 Docker Swarm 模式下,使用 deploy.replicas 配置:
yaml
version: '3.8'
services:
web:
image: nginx
deploy:
replicas: 3
resources:
limits:
cpus: '0.5'
memory: 512M动态扩缩容
sh
# 扩展服务
docker service scale myapp_web=5
# 缩减服务
docker service scale myapp_web=2负载均衡
当有多个服务实例时,Docker 会自动进行负载均衡。
yaml
services:
web:
image: nginx
ports:
- "8080:80"运行多个实例:
sh
docker compose up -d --scale web=3访问 http://localhost:8080 时,请求会被分发到不同的实例。
依赖顺序
使用 depends_on 时,Compose 会等待依赖服务启动:
yaml
services:
web:
depends_on:
- db
deploy:
replicas: 3
db:
image: postgres:15
deploy:
replicas: 1健康检查
使用健康检查确保服务正常:
yaml
services:
web:
image: nginx
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost"]
interval: 30s
timeout: 10s
retries: 3
start_period: 40s滚动更新
在 Swarm 模式下,可以配置滚动更新:
yaml
services:
web:
image: nginx:latest
deploy:
replicas: 5
update_config:
parallelism: 2
delay: 10s
failure_action: rollback