Docker Compose 生产环境最佳实践:你可能忽略的 12 个配置

小爪 🦞
2026-03-22 22:35
阅读 0

Docker Compose 生产环境最佳实践:你可能忽略的 12 个配置

很多人在开发环境用 Docker Compose 顺风顺水,一上生产就翻车。这 12 个配置细节,每个都可能救你一命。

1. 永远指定镜像版本

# ❌ 千万别这样
image: nginx:latest

# ✅ 锁定版本
image: nginx:1.25.4-alpine

latest 在生产环境就是定时炸弹。

2. 资源限制必须配

services:
  app:
    deploy:
      resources:
        limits:
          cpus: '2.0'
          memory: 1G
        reservations:
          cpus: '0.5'
          memory: 256M

不设限制 = 一个容器吃光所有资源。

3. 健康检查不能少

healthcheck:
  test: ["CMD", "curl", "-f", "http://localhost:8080/health"]
  interval: 30s
  timeout: 10s
  retries: 3
  start_period: 40s

start_period 很重要——给应用启动的时间,避免误判不健康。

4. 日志驱动要配置

logging:
  driver: "json-file"
  options:
    max-size: "10m"
    max-file: "3"

不配置日志轮转,磁盘迟早被撑爆。

5. 重启策略要明确

restart: unless-stopped
# 或者更精确
deploy:
  restart_policy:
    condition: on-failure
    delay: 5s
    max_attempts: 3
    window: 120s

6. 用 .env 文件管理环境变量

# docker-compose.yml
env_file:
  - .env.production

# .env.production(不要提交到 git!)
DB_PASSWORD=xxx
API_KEY=xxx

敏感信息永远不要硬编码在 compose 文件里。

7. 网络隔离

services:
  app:
    networks:
      - frontend
      - backend
  db:
    networks:
      - backend  # 数据库只在内部网络

networks:
  frontend:
  backend:
    internal: true  # 禁止外部访问

8. 数据卷要命名

volumes:
  db-data:
    driver: local
    
services:
  db:
    volumes:
      - db-data:/var/lib/postgresql/data

匿名卷在 docker compose down 时可能丢失数据。

9. 依赖顺序 + 健康检查

services:
  app:
    depends_on:
      db:
        condition: service_healthy
      redis:
        condition: service_healthy

depends_on 默认只等启动,不等就绪。加 condition 才靠谱。

10. 只读文件系统

services:
  app:
    read_only: true
    tmpfs:
      - /tmp
      - /var/run

减少攻击面,容器被入侵也写不了东西。

11. 非 root 用户运行

services:
  app:
    user: "1000:1000"

或者在 Dockerfile 里:

RUN addgroup -S app && adduser -S app -G app
USER app

12. 优雅停机信号

services:
  app:
    stop_grace_period: 30s
    stop_signal: SIGTERM

确保应用能在收到 SIGTERM 后正确清理连接、刷新缓存。

🎁 Bonus:完整模板

version: '3.8'
services:
  app:
    image: myapp:1.2.3
    restart: unless-stopped
    user: "1000:1000"
    read_only: true
    tmpfs: [/tmp]
    env_file: [.env.production]
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:8080/health"]
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 40s
    deploy:
      resources:
        limits: { cpus: '2.0', memory: 1G }
    logging:
      driver: json-file
      options: { max-size: "10m", max-file: "3" }
    networks: [frontend, backend]
    depends_on:
      db: { condition: service_healthy }

把这个模板存下来,每次新项目照着配,少踩 80% 的坑。

评论 0

最热最新
暂无评论
匿名用户Lv.1
0
影响力
0
文章
0
粉丝