Docker Compose 生产部署实战

Choyeon· 2026年8月25日· 1 分钟阅读· 540 阅读· 386 字· 1,181 字符
Docker Compose 生产部署实战

容器化部署已成为现代应用交付的标准方式,Docker Compose 能快速编排多服务架构,但生产环境需要更多稳定性保障措施。

服务配置与资源限制

为每个服务配置合理的 CPU 和内存限制,防止单点故障拖垮宿主机。配合 healthcheck 确保服务异常时自动重启。

version: "3.9"
services:
  web:
    build: { context: ., dockerfile: Dockerfile, target: production }
    image: registry.example.com/app:${TAG:-latest}
    restart: unless-stopped
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost/health"]
      interval: 30s
      timeout: 5s
      retries: 3
      start_period: 40s
    deploy:
      resources:
        limits: { cpus: "2.0", memory: 2G }
        reservations: { cpus: "0.5", memory: 512M }
    logging:
      driver: json-file
      options: { max-size: "10m", max-file: "5" }
    networks: [frontend, backend]
    secrets: [db_password]
    depends_on:
      db: { condition: service_healthy }
  db:
    image: postgres:16-alpine
    volumes: [pgdata:/var/lib/postgresql/data]
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U app"]
      interval: 10s
      timeout: 5s
      retries: 5
volumes: { pgdata: null }
networks: { frontend: null, backend: { internal: true } }
secrets: { db_password: { file: ./secrets/db_password.txt } }

网络与安全隔离

将数据库等内部服务放入 internal 网络,不对外暴露端口。敏感凭证通过 secrets 机制挂载,避免硬编码进镜像。

配置项 开发环境 生产环境 推荐值
restart no unless-stopped 生产必开
healthcheck 可选 必须 30s间隔/3次重试
resource limits 无 必须 CPU 2C/内存 2G
logging driver 默认 json-file max-size 10m
network mode bridge 分frontend/backend internal隔离DB

最佳实践

使用多阶段构建减小镜像体积,结合 .dockerignore 排除无关文件,定期清理悬空镜像和卷。

本文作者

评论 (0)

暂无评论,来抢沙发吧。