引言

把 Demo 跑起来只是第一步,让服务稳定运行在生产环境才是真正的考验。本文将带你完成 OpenClaw 的全链路部署:Docker 镜像构建 → Compose 编排 → K8s 部署 → CI/CD 自动化 → 监控告警

一、Dockerfile 最佳实践

多阶段构建

# ---- 构建阶段 ----
FROM golang:1.21-alpine AS builder

WORKDIR /src
RUN go env -w GOPROXY=https://goproxy.cn,direct

COPY go.mod go.sum ./
RUN go mod download

COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /out/opencLaw ./cmd/opencLaw

# ---- 运行阶段 ----
FROM alpine:3.19

RUN apk add --no-cache ca-certificates tzdata && \
    adduser -D -u 10001 appuser

COPY --from=builder /out/opencLaw /usr/local/bin/opencLaw
COPY --from=builder /src/config /etc/opencLaw/config

USER appuser
WORKDIR /app
EXPOSE 8080

ENTRYPOINT ["/usr/local/bin/opencLaw"]
CMD ["--config=/etc/opencLaw/config/prod.yaml"]

最终镜像大小约 18MB(对比单阶段构建 800MB+),冷启动时间 < 200ms。

镜像构建命令

docker build -t openclaw/opencLaw:1.0.0 .
docker push openclaw/opencLaw:1.0.0

二、Docker Compose 编排

适合单机部署或小规模场景:

# docker-compose.yml
version: '3.8'

x-common-env: &common-env
  LOG_LEVEL: info
  METRICS_ADDR: :9090

services:
  openclaw:
    image: openclaw/opencLaw:1.0.0
    restart: unless-stopped
    ports:
      - "8080:8080"
      - "9090:9090"
    environment:
      <<: *common-env
      DB_DSN: postgres://claw:${DB_PASSWORD}@postgres:5432/openclaw
      REDIS_ADDR: redis:6379
    depends_on:
      postgres: { condition: service_healthy }
      redis:    { condition: service_healthy }
    volumes:
      - ./data:/app/data
    healthcheck:
      test: ["CMD", "wget", "--spider", "-q", "http://localhost:8080/healthz"]
      interval: 30s
      timeout: 5s
      retries: 3
    deploy:
      resources:
        limits: { cpus: '2.0', memory: 1G }
        reservations: { cpus: '0.5', memory: 256M }

  postgres:
    image: postgres:16-alpine
    restart: unless-stopped
    environment:
      POSTGRES_USER: claw
      POSTGRES_PASSWORD: ${DB_PASSWORD}
      POSTGRES_DB: openclaw
    volumes:
      - pgdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U claw"]
      interval: 10s
      timeout: 3s
      retries: 5

  redis:
    image: redis:7-alpine
    restart: unless-stopped
    command: ["redis-server", "--appendonly", "yes"]
    volumes:
      - redisdata:/data
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 10s

  prometheus:
    image: prom/prometheus:v2.50.0
    ports:
      - "9091:9090"
    volumes:
      - ./monitoring/prometheus.yml:/etc/prometheus/prometheus.yml

volumes:
  pgdata:
  redisdata:

启动:

docker compose up -d
docker compose logs -f openclaw

三、K8s Helm Chart 部署

Helm Chart 结构

openclaw-chart/
├── Chart.yaml
├── values.yaml
├── templates/
│   ├── deployment.yaml
│   ├── service.yaml
│   ├── ingress.yaml
│   ├── configmap.yaml
│   ├── secret.yaml
│   ├── hpa.yaml
│   └── serviceaccount.yaml
└── README.md

values.yaml 关键片段

replicaCount: 3

image:
  repository: openclaw/opencLaw
  tag: "1.0.0"
  pullPolicy: IfNotPresent

resources:
  requests: { cpu: 200m, memory: 256Mi }
  limits:   { cpu: 1000m, memory: 1Gi }

autoscaling:
  enabled: true
  minReplicas: 3
  maxReplicas: 20
  targetCPUUtilizationPercentage: 70
  targetMemoryUtilizationPercentage: 80

ingress:
  enabled: true
  className: nginx
  hosts:
    - host: api.guide-openclaw.vip
      paths: [{ path: /, pathType: Prefix }]
  tls:
    - hosts: [api.guide-openclaw.vip]
      secretName: openclaw-tls

postgresql:
  enabled: true
  auth:
    username: claw
    password: <your-password>
    database: openclaw

redis:
  enabled: true
  auth:
    password: <your-password>

安装命令

helm repo add openclaw https://charts.openclaw.io
helm install openclaw openclaw/openclaw \
  --namespace openclaw --create-namespace \
  --values values.yaml

四、CI/CD 流水线(GitHub Actions)

# .github/workflows/deploy.yml
name: Build and Deploy

on:
  push:
    branches: [main]
    tags: ['v*']

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Set up Go
        uses: actions/setup-go@v5
        with:
          go-version: '1.21'

      - name: Build & Test
        run: |
          go test ./...
          go build -o bin/opencLaw ./cmd/opencLaw

      - name: Build & Push Image
        uses: docker/build-push-action@v5
        with:
          push: true
          tags: |
            ghcr.io/${{ github.repository }}:${{ github.sha }}
            ghcr.io/${{ github.repository }}:latest

  deploy:
    needs: build
    runs-on: ubuntu-latest
    if: startsWith(github.ref, 'refs/tags/v')
    steps:
      - uses: azure/k8s-set-context@v3
        with:
          kube-context: ${{ secrets.KUBE_CONTEXT }}

      - run: |
          helm upgrade --install openclaw ./openclaw-chart \
            --set image.tag=${{ github.ref_name }} \
            --namespace openclaw

五、监控告警

Prometheus 指标

OpenClaw 内置 metrics,默认暴露在 :9090/metrics,对接 Prometheus 后可以看到:

  • opencLaw_request_total{path, status}
  • opencLaw_request_duration_seconds{path}
  • opencLaw_plugin_execution_total{plugin, status}
  • opencLaw_go_goroutines

Grafana Dashboard

我们提供官方 Dashboard:OpenClaw Grafana Dashboard ID 18842

导入后即可看到开箱即用的可视化面板。

告警规则示例

# alerts.yaml
groups:
- name: openclaw
  rules:
  - alert: OpenClawHighErrorRate
    expr: |
      sum(rate(opencLaw_request_total{status=~"5.."}[5m])) 
      / sum(rate(opencLaw_request_total[5m])) > 0.05
    for: 5m
    labels:
      severity: critical
    annotations:
      summary: "OpenClaw 错误率超过 5%"

  - alert: OpenClawHighLatency
    expr: |
      histogram_quantile(0.95, sum(rate(opencLaw_request_duration_seconds_bucket[5m])) by (le)) > 1
    for: 10m
    labels:
      severity: warning

六、灾备与恢复

数据库每日备份

# /etc/cron.d/openclaw-backup
0 2 * * *         pg_dump -U claw openclaw | gzip > /backup/openclaw-$(date +\%Y\%m\%d).sql.gz
0 3 * * *         find /backup -name "openclaw-*.sql.gz" -mtime +7 -delete

蓝绿发布

# 部署 v2(绿色)
helm install openclaw-green openclaw/openclaw --set image.tag=v2.0.0

# 验证 v2 健康
kubectl get pods -l app=openclaw,release=openclaw-green

# 切换流量
kubectl patch service openclaw -p '{"spec":{"selector":{"release":"openclaw-green"}}}'

# 旧版本下线
helm uninstall openclaw-blue

总结

生产环境的稳定运行不是一蹴而就的,建议按以下顺序逐步落地:

  1. ✅ 先跑通 Docker Compose(验证业务)
  2. ✅ 上 K8s + Helm(提升弹性)
  3. ✅ 接 CI/CD(自动化发布)
  4. ✅ 加监控告警(可观测性)
  5. ✅ 完善灾备流程(业务连续性)

延伸阅读