不止一叶代码屋 个人技术博客 · 代码与生活的记录

工程实践

Docker Compose 部署全栈项目的完整清单

目录结构

project/
├── docker-compose.yml
├── .env
├── web/
│   └── Dockerfile
└── nginx/
    └── default.conf

Compose 文件骨架

services:
  web:
    build: ./web
    env_file: .env
    restart: unless-stopped
    depends_on:
      db:
        condition: service_healthy
    healthcheck:
      test: ['CMD', 'curl', '-f', 'http://localhost:3000/health']
      interval: 30s
      timeout: 5s
      retries: 3

  db:
    image: postgres:16-alpine
    volumes:
      - db-data:/var/lib/postgresql/data
    healthcheck:
      test: ['CMD-SHELL', 'pg_isready -U postgres']
      interval: 10s

volumes:
  db-data:

容易被忽略的点

健康检查不是可选项

没有 healthcheck,depends_on 只保证容器启动顺序,不保证服务可用。数据库还在初始化,web 已经开始连了。

时区

容器默认 UTC,日志时间会跟本地差 8 小时:

environment:
  - TZ=Asia/Shanghai

日志会撑爆磁盘

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

不限制的话,跑几个月能占满整个盘。

不要用 latest 标签

image: postgres:16-alpine   # 好
image: postgres:latest      # 别

latest 会在你不知情的时候升级,然后挂掉。

常用命令

docker compose up -d          # 启动
docker compose logs -f web    # 看日志
docker compose exec web sh    # 进容器
docker compose down -v        # 停止并删数据卷(谨慎)

小结

Compose 的上手门槛很低,但生产可用和能跑起来之间差着健康检查、日志限制、时区、数据卷这一整套配置。这份清单可以当检查表用。

订阅 RSS

← 返回首页