ガイド

在VPS上运行生产级Docker Compose栈

中級25分で読めます更新日 2026年6月27日
短い回答

可用的生产栈包括:Caddy自动管理TLS证书、你的应用、PostgreSQL和Redis,全部在一个Compose文件中定义,使用具名卷和健康检查。在8GB内存和NVMe硬盘上,这足以应对大量流量;每次部署前创建快照,回滚只需两分钟。

01 从官方源安装Docker

Distribution packages lag significantly. The convenience script is fine on a fresh instance.

curl -fsSL https://get.docker.com | sh
systemctl enable --now docker

02 编写Compose文件

Caddy obtains and renews certificates automatically, which removes the single most common source of production breakage.

services:
  caddy:
    image: caddy:2-alpine
    restart: unless-stopped
    ports: ["80:80", "443:443", "443:443/udp"]
    volumes:
      - ./Caddyfile:/etc/caddy/Caddyfile:ro
      - caddy_data:/data
  app:
    build: .
    restart: unless-stopped
    depends_on: { db: { condition: service_healthy } }
    environment:
      DATABASE_URL: postgres://app:${DB_PASS}@db:5432/app
  db:
    image: postgres:17-alpine
    restart: unless-stopped
    environment:
      POSTGRES_USER: app
      POSTGRES_PASSWORD: ${DB_PASS}
    volumes: [pgdata:/var/lib/postgresql/data]
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U app"]
      interval: 10s
volumes: { caddy_data: {}, pgdata: {} }

03 配置Caddy

Three lines is a complete TLS-terminating reverse proxy with automatic certificate renewal.

app.example.com {
  encode zstd gzip
  reverse_proxy app:8000
}

04 备份数据库,而非容器

A file copy of a running Postgres data directory produces a corrupt backup that appears to succeed. Dump it properly.

docker compose exec -T db pg_dump -U app app | zstd > /backups/app-$(date +%F).sql.zst

05 每次部署前创建快照

Free, instant, and it converts a failed deployment from an incident into a rollback.

よくある質問

这需要多少内存?

把各容器内存上限相加,再加约1GB留给宿主机。此栈在8GB内存下运行绰绰有余。

我应该改用Docker Swarm还是Kubernetes?

对于单台服务器来说不要。在真正拥有多个节点之前,Compose是正确的工具。