指南

在VPS上运行生产级Docker Compose技术栈

中级阅读时间 25 分钟更新时间 2026年6月27日
简短回答

一个可行的生产级堆栈包括用于自动TLS的Caddy、你的应用程序、PostgreSQL和Redis,全部定义在一个Compose文件中,带有命名卷和健康检查。在8 GB内存和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.

常见问题

这需要多少内存?

总和容器内存限制再加上约1 GB给主机。该堆栈在8 GB下运行舒适。

Should I use Docker Swarm or Kubernetes instead?

不适用于单台服务器。在您真正拥有多个节点之前,Compose 是正确的工具。