# k3s / k8s 安装

Source: https://cch-plus.com/zh-CN/docs/installation/kubernetes

> 在一台 k3s 节点上用 11 个清单文件部署 CCHP：保存文件、填写域名与密钥、部署并完成安装向导，以及备份、升级与卸载。

本页在一台 k3s 节点上部署 CCHP。Docker Compose 在一个容器中运行全部角色；这里 control（控制台与管理 API）、gateway（LLM 网关）和 worker（后台任务）各是一个独立的工作负载，有各自的资源上限、健康检查和日志，可以单独重启。数据库使用同一节点上的单实例 PostgreSQL 18（含 TimescaleDB）与 Dragonfly。已经用 k3s 管理服务器，或者希望按角色限制资源时，选择本页；否则 [Docker Compose 安装](https://cch-plus.com/zh-CN/docs/installation/docker-compose) 更简单。

```mermaid
%% caption: k3s 单节点部署的组件
graph LR
  B[浏览器] -->|HTTPS| I[ingress-nginx]
  L[LLM 客户端] -->|HTTPS| I
  I --> C[control]
  I --> G[gateway]
  M[cchp-migrate] --> P[(postgres)]
  C --> P
  G --> P
  W[worker] --> P
  C --> D[(dragonfly)]
  G --> D
  W --> D
  G --> U[上游供应商]
```

## 准备工作

- 一台 Linux 服务器（amd64 或 arm64），已安装 k3s，并关闭 k3s 自带的 Traefik。新装 k3s 时：

  ```bash
  curl -sfL https://get.k3s.io | sh -s - --disable=traefik
  ```

- 已安装 [ingress-nginx](https://kubernetes.github.io/ingress-nginx/deploy/) 入口控制器（官方生产清单也支持通过 Gateway API / Envoy Gateway 暴露入口 (since v1.0.13)）。清单中的 Ingress 用 ingress-nginx 的注解关闭流式响应的缓冲，并把读写超时设为 3600 秒。

- 两个域名，DNS 都指向这台服务器：控制台域名（本页用 `cchp.example.com`）与 API 域名（本页用 `api.cchp.example.com`）。另备一份同时覆盖两个域名的 TLS 证书与私钥。

- 内存：各工作负载的内存上限合计 5 GiB，另需留出 k3s 与入口控制器本身的用量。

- 磁盘：k3s 自带的 local-path 存储不限制卷的容量，所有卷共用节点磁盘。清单中的卷申领合计约 481 GiB，建议节点磁盘不小于这个值。

- 服务器能访问 `ghcr.io`、Docker Hub、`docker.dragonflydb.io` 与 `cch-plus.com`（模型价格表）。

本页的命令都在这台服务器上以 root 用户执行，k3s 自带 `kubectl`。

## 第 1 步：保存清单文件

新建目录 `cchp-k3s`，把下面 11 个文件保存进去：

```bash
mkdir cchp-k3s
```

命名空间：

```yaml filename="cchp-k3s/00-namespace.yaml"
apiVersion: v1
kind: Namespace
metadata:
  name: cchp
```

数据库密码与密钥。占位值在第 2 步替换：

```yaml filename="cchp-k3s/01-secrets.yaml"
# 占位值在第 2 步替换为随机值
apiVersion: v1
kind: Secret
metadata:
  name: cchp-migration-secrets
  namespace: cchp
stringData:
  POSTGRES_PASSWORD: CHANGE_ME_OWNER_PASSWORD
  ATLAS_DATABASE_URL: postgres://hub:CHANGE_ME_OWNER_PASSWORD@postgres:5432/app?sslmode=disable
  CCHP_DATABASE_RUNTIME_PASSWORD: CHANGE_ME_RUNTIME_PASSWORD
---
apiVersion: v1
kind: Secret
metadata:
  name: cchp-secrets
  namespace: cchp
stringData:
  DATABASE_URL: postgres://cchp_runtime:CHANGE_ME_RUNTIME_PASSWORD@postgres:5432/app?sslmode=disable
  DRAGONFLY_URL: redis://dragonfly:6379/0
  CCH_TOKEN_PEPPER: CHANGE_ME_TOKEN_PEPPER
  CCH_MASTER_KEY: CHANGE_ME_MASTER_KEY
  DRAGONFLY_KEY_SECRET: CHANGE_ME_DRAGONFLY_KEY_SECRET
```

共享配置。三个地址在第 2 步替换：

```yaml filename="cchp-k3s/02-config.yaml"
apiVersion: v1
kind: ConfigMap
metadata:
  name: cchp-config
  namespace: cchp
data:
  APP_ENV: production
  CCHP_DATABASE_RUNTIME_ROLE: cchp_runtime
  CCH_PUBLIC_BASE_URL: https://cchp.example.com # 控制台地址
  CCH_CONTROL_PLANE_ALLOWED_ORIGINS: https://cchp.example.com # 与控制台地址相同
  CCH_GATEWAY_PUBLIC_URL: https://api.cchp.example.com # API 地址
  CCH_SIEM_MODE: disabled # 不向外部 SIEM 投递审计事件
  # 数据库所在磁盘的容量：local-path 的卷都在同一块磁盘上，读共享卷即可
  CCHP_DATABASE_STORAGE_SOURCE: filesystem
  CCHP_DATABASE_STORAGE_PATH: /var/lib/cchp/data/objectstore
```

control、gateway 与 worker 共用的两个卷：

```yaml filename="cchp-k3s/03-volumes.yaml"
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: cchp-objectstore
  namespace: cchp
spec:
  accessModes: ["ReadWriteOnce"]
  resources:
    requests:
      storage: 20Gi
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: cchp-task-results
  namespace: cchp
spec:
  accessModes: ["ReadWriteOnce"]
  resources:
    requests:
      storage: 50Gi
```

PostgreSQL：

```yaml filename="cchp-k3s/04-postgres.yaml"
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: postgres
  namespace: cchp
spec:
  serviceName: postgres
  selector:
    matchLabels:
      app.kubernetes.io/name: postgres
  template:
    metadata:
      labels:
        app.kubernetes.io/name: postgres
    spec:
      terminationGracePeriodSeconds: 60
      securityContext:
        runAsNonRoot: true
        runAsUser: 70
        runAsGroup: 70
        fsGroup: 70
        seccompProfile:
          type: RuntimeDefault
      containers:
        - name: postgres
          image: timescale/timescaledb:2.31.0-pg18
          args:
            - postgres
            - -c
            - shared_preload_libraries=timescaledb,pg_stat_statements
            - -c
            - pg_stat_statements.max=10000
            - -c
            - track_io_timing=on
            - -c
            - max_connections=200
          env:
            - name: POSTGRES_USER
              value: hub
            - name: POSTGRES_DB
              value: app
            - name: POSTGRES_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: cchp-migration-secrets
                  key: POSTGRES_PASSWORD
            - name: POSTGRES_INITDB_ARGS
              value: --auth-host=scram-sha-256
            - name: PGDATA
              value: /var/lib/postgresql/data/pgdata
          ports:
            - name: postgres
              containerPort: 5432
          readinessProbe:
            exec:
              command: ["sh", "-c", "pg_isready -h 127.0.0.1 -U hub -d app"]
            periodSeconds: 5
          livenessProbe:
            tcpSocket:
              port: postgres
            initialDelaySeconds: 30
            failureThreshold: 6
          resources:
            requests:
              cpu: 250m
              memory: 512Mi
            limits:
              memory: 2Gi
          securityContext:
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities:
              drop: ["ALL"]
          volumeMounts:
            - name: data
              mountPath: /var/lib/postgresql/data
            - name: run
              mountPath: /var/run/postgresql
            - name: tmp
              mountPath: /tmp
      volumes:
        - name: run
          emptyDir: {}
        - name: tmp
          emptyDir: {}
  volumeClaimTemplates:
    - metadata:
        name: data
      spec:
        accessModes: ["ReadWriteOnce"]
        resources:
          requests:
            storage: 20Gi
---
apiVersion: v1
kind: Service
metadata:
  name: postgres
  namespace: cchp
spec:
  selector:
    app.kubernetes.io/name: postgres
  ports:
    - port: 5432
```

Dragonfly：

```yaml filename="cchp-k3s/05-dragonfly.yaml"
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: dragonfly
  namespace: cchp
spec:
  serviceName: dragonfly
  selector:
    matchLabels:
      app.kubernetes.io/name: dragonfly
  template:
    metadata:
      labels:
        app.kubernetes.io/name: dragonfly
    spec:
      securityContext:
        runAsNonRoot: true
        runAsUser: 999
        runAsGroup: 999
        fsGroup: 999
        seccompProfile:
          type: RuntimeDefault
      containers:
        - name: dragonfly
          image: docker.dragonflydb.io/dragonflydb/dragonfly:v2.0.2
          args: ["--proactor_threads=2", "--maxmemory=768mb", "--dir=/data"]
          ports:
            - name: redis
              containerPort: 6379
          readinessProbe:
            exec:
              command: ["redis-cli", "ping"]
            periodSeconds: 5
          livenessProbe:
            tcpSocket:
              port: redis
            initialDelaySeconds: 10
            failureThreshold: 6
          resources:
            requests:
              cpu: 100m
              memory: 256Mi
            limits:
              memory: 1Gi
          securityContext:
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities:
              drop: ["ALL"]
          volumeMounts:
            - name: data
              mountPath: /data
  volumeClaimTemplates:
    - metadata:
        name: data
      spec:
        accessModes: ["ReadWriteOnce"]
        resources:
          requests:
            storage: 2Gi
---
apiVersion: v1
kind: Service
metadata:
  name: dragonfly
  namespace: cchp
spec:
  selector:
    app.kubernetes.io/name: dragonfly
  ports:
    - port: 6379
```

数据库迁移。control、gateway 与 worker 的初始化容器 `wait-for-migrations` 等它完成后才启动各自的进程：

```yaml filename="cchp-k3s/06-migrate-job.yaml"
apiVersion: batch/v1
kind: Job
metadata:
  name: cchp-migrate
  namespace: cchp
spec:
  activeDeadlineSeconds: 51840
  ttlSecondsAfterFinished: 3600
  template:
    spec:
      restartPolicy: Never
      securityContext:
        runAsNonRoot: true
        seccompProfile:
          type: RuntimeDefault
      containers:
        - name: migrate
          image: ghcr.io/cch-hq/cch-plus:latest
          imagePullPolicy: IfNotPresent
          command: ["/usr/local/bin/migrate"]
          args: ["apply"]
          env:
            - name: APP_ENV
              valueFrom:
                configMapKeyRef:
                  name: cchp-config
                  key: APP_ENV
            - name: CCHP_DATABASE_RUNTIME_ROLE
              valueFrom:
                configMapKeyRef:
                  name: cchp-config
                  key: CCHP_DATABASE_RUNTIME_ROLE
            - name: ATLAS_DATABASE_URL
              valueFrom:
                secretKeyRef:
                  name: cchp-migration-secrets
                  key: ATLAS_DATABASE_URL
            - name: CCHP_DATABASE_RUNTIME_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: cchp-migration-secrets
                  key: CCHP_DATABASE_RUNTIME_PASSWORD
            - name: CCH_MASTER_KEY
              valueFrom:
                secretKeyRef:
                  name: cchp-secrets
                  key: CCH_MASTER_KEY
            - name: CCH_SCRATCH_DIR
              value: /var/cache/cchp
          resources:
            requests:
              cpu: 100m
              memory: 128Mi
            limits:
              cpu: "1"
              memory: 512Mi
          securityContext:
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities:
              drop: ["ALL"]
          volumeMounts:
            - name: scratch
              mountPath: /var/cache/cchp
      volumes:
        - name: scratch
          emptyDir: {}
```

control：

```yaml filename="cchp-k3s/07-control.yaml"
apiVersion: apps/v1
kind: Deployment
metadata:
  name: control
  namespace: cchp
spec:
  replicas: 1
  selector:
    matchLabels:
      app: control
  template:
    metadata:
      labels:
        app: control
    spec:
      securityContext:
        runAsNonRoot: true
        fsGroup: 65532
        fsGroupChangePolicy: OnRootMismatch
        seccompProfile:
          type: RuntimeDefault
      initContainers:
        - name: wait-for-migrations
          image: ghcr.io/cch-hq/cch-plus:latest
          imagePullPolicy: IfNotPresent
          args: ["db", "wait", "--timeout=864m"]
          env:
            - name: DATABASE_URL
              valueFrom:
                secretKeyRef:
                  name: cchp-secrets
                  key: DATABASE_URL
            - name: CCHP_DATABASE_RUNTIME_ROLE
              valueFrom:
                configMapKeyRef:
                  name: cchp-config
                  key: CCHP_DATABASE_RUNTIME_ROLE
          resources:
            requests:
              cpu: 10m
              memory: 64Mi
            limits:
              cpu: 200m
              memory: 256Mi
          securityContext:
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities:
              drop: ["ALL"]
      containers:
        - name: control
          image: ghcr.io/cch-hq/cch-plus:latest
          imagePullPolicy: IfNotPresent
          args: ["api", "--role=control"]
          envFrom:
            - configMapRef:
                name: cchp-config
            - secretRef:
                name: cchp-secrets
          env:
            - name: POD_IP
              valueFrom:
                fieldRef:
                  fieldPath: status.podIP
            - name: CCH_NODE_INTERNAL_URL
              value: http://$(POD_IP):8092
            - name: CCH_CONTROL_OBSERVABILITY_ADDR
              value: ":8085"
          ports:
            - name: http
              containerPort: 8080
            - name: node-internal
              containerPort: 8092
            - name: metrics
              containerPort: 8085
          livenessProbe:
            httpGet: { path: /livez, port: http }
            initialDelaySeconds: 30
          readinessProbe:
            httpGet: { path: /readyz, port: http }
            initialDelaySeconds: 5
            periodSeconds: 5
            failureThreshold: 2
          startupProbe:
            httpGet: { path: /livez, port: http }
            periodSeconds: 5
            failureThreshold: 30
          resources:
            requests:
              cpu: 100m
              memory: 256Mi
            limits:
              cpu: "2"
              memory: 512Mi
          securityContext:
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities:
              drop: ["ALL"]
          volumeMounts:
            - name: objectstore
              mountPath: /var/lib/cchp/data/objectstore
            - name: task-results
              mountPath: /var/lib/cchp/data/task-results
            - name: scratch
              mountPath: /var/cache/cchp
      volumes:
        - name: objectstore
          persistentVolumeClaim:
            claimName: cchp-objectstore
        - name: task-results
          persistentVolumeClaim:
            claimName: cchp-task-results
        - name: scratch
          ephemeral:
            volumeClaimTemplate:
              spec:
                accessModes: ["ReadWriteOnce"]
                resources:
                  requests:
                    storage: 64Gi
---
apiVersion: v1
kind: Service
metadata:
  name: control
  namespace: cchp
spec:
  selector:
    app: control
  ports:
    - port: 8080
```

gateway：

```yaml filename="cchp-k3s/08-gateway.yaml"
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: gateway
  namespace: cchp
spec:
  serviceName: gateway-hl
  replicas: 1
  selector:
    matchLabels:
      app: gateway
  template:
    metadata:
      labels:
        app: gateway
    spec:
      # 停止前最多等待 900 秒，让进行中的请求结束
      terminationGracePeriodSeconds: 930
      securityContext:
        runAsNonRoot: true
        fsGroup: 65532
        fsGroupChangePolicy: OnRootMismatch
        seccompProfile:
          type: RuntimeDefault
      initContainers:
        - name: wait-for-migrations
          image: ghcr.io/cch-hq/cch-plus:latest
          imagePullPolicy: IfNotPresent
          args: ["db", "wait", "--timeout=864m"]
          env:
            - name: DATABASE_URL
              valueFrom:
                secretKeyRef:
                  name: cchp-secrets
                  key: DATABASE_URL
            - name: CCHP_DATABASE_RUNTIME_ROLE
              valueFrom:
                configMapKeyRef:
                  name: cchp-config
                  key: CCHP_DATABASE_RUNTIME_ROLE
          resources:
            requests:
              cpu: 10m
              memory: 64Mi
            limits:
              cpu: 200m
              memory: 256Mi
          securityContext:
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities:
              drop: ["ALL"]
      containers:
        - name: gateway
          image: ghcr.io/cch-hq/cch-plus:latest
          imagePullPolicy: IfNotPresent
          args: ["api", "--role=gateway", "--addr=:8081"]
          envFrom:
            - configMapRef:
                name: cchp-config
            - secretRef:
                name: cchp-secrets
          env:
            - name: POD_NAME
              valueFrom:
                fieldRef:
                  fieldPath: metadata.name
            - name: CCH_ARCHIVE_INTERNAL_URL
              value: http://$(POD_NAME).gateway-hl:8091
            - name: CCH_GATEWAY_OBSERVABILITY_ADDR
              value: ":8084"
            - name: CCH_REPLAY_OWNER_PROXY_NODES
              value: gateway-0=http://gateway-0.gateway-hl:8081
            - name: CCH_ALLOW_EMPTY_ROUTING_BOOTSTRAP
              value: "true"
          ports:
            - name: http
              containerPort: 8081
            - name: archive
              containerPort: 8091
            - name: metrics
              containerPort: 8084
          livenessProbe:
            httpGet: { path: /livez, port: http }
            initialDelaySeconds: 30
          readinessProbe:
            httpGet: { path: /readyz, port: http }
            initialDelaySeconds: 5
            periodSeconds: 5
            failureThreshold: 2
          startupProbe:
            httpGet: { path: /livez, port: http }
            periodSeconds: 5
            failureThreshold: 30
          resources:
            requests:
              cpu: 250m
              memory: 256Mi
            limits:
              cpu: "2"
              memory: 1Gi
          securityContext:
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities:
              drop: ["ALL"]
          volumeMounts:
            - name: objectstore
              mountPath: /var/lib/cchp/data/objectstore
            - name: task-results
              mountPath: /var/lib/cchp/data/task-results
            - name: archive
              mountPath: /var/lib/cchp/node
            - name: scratch
              mountPath: /var/cache/cchp
      volumes:
        - name: objectstore
          persistentVolumeClaim:
            claimName: cchp-objectstore
        - name: task-results
          persistentVolumeClaim:
            claimName: cchp-task-results
        - name: scratch
          ephemeral:
            volumeClaimTemplate:
              spec:
                accessModes: ["ReadWriteOnce"]
                resources:
                  requests:
                    storage: 9Gi
  volumeClaimTemplates:
    - metadata:
        name: archive
      spec:
        accessModes: ["ReadWriteOnce"]
        resources:
          requests:
            storage: 16Gi
---
apiVersion: v1
kind: Service
metadata:
  name: gateway
  namespace: cchp
spec:
  selector:
    app: gateway
  ports:
    - port: 8081
---
# 每个 gateway Pod 的固定 DNS 名称
apiVersion: v1
kind: Service
metadata:
  name: gateway-hl
  namespace: cchp
spec:
  clusterIP: None
  publishNotReadyAddresses: true
  selector:
    app: gateway
  ports:
    - name: http
      port: 8081
    - name: archive
      port: 8091
```

worker：

```yaml filename="cchp-k3s/09-worker.yaml"
apiVersion: apps/v1
kind: Deployment
metadata:
  name: worker
  namespace: cchp
spec:
  # 只能运行 1 个副本
  replicas: 1
  selector:
    matchLabels:
      app: worker
  template:
    metadata:
      labels:
        app: worker
    spec:
      terminationGracePeriodSeconds: 45
      securityContext:
        runAsNonRoot: true
        fsGroup: 65532
        fsGroupChangePolicy: OnRootMismatch
        seccompProfile:
          type: RuntimeDefault
      initContainers:
        - name: wait-for-migrations
          image: ghcr.io/cch-hq/cch-plus:latest
          imagePullPolicy: IfNotPresent
          args: ["db", "wait", "--timeout=864m"]
          env:
            - name: DATABASE_URL
              valueFrom:
                secretKeyRef:
                  name: cchp-secrets
                  key: DATABASE_URL
            - name: CCHP_DATABASE_RUNTIME_ROLE
              valueFrom:
                configMapKeyRef:
                  name: cchp-config
                  key: CCHP_DATABASE_RUNTIME_ROLE
          resources:
            requests:
              cpu: 10m
              memory: 64Mi
            limits:
              cpu: 200m
              memory: 256Mi
          securityContext:
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities:
              drop: ["ALL"]
      containers:
        - name: worker
          image: ghcr.io/cch-hq/cch-plus:latest
          imagePullPolicy: IfNotPresent
          args: ["api", "--role=worker"]
          envFrom:
            - configMapRef:
                name: cchp-config
            - secretRef:
                name: cchp-secrets
          env:
            - name: CCH_WORKER_OBSERVABILITY_ADDR
              value: ":8082"
            - name: POD_IP
              valueFrom:
                fieldRef:
                  fieldPath: status.podIP
            - name: CCH_NODE_INTERNAL_URL
              value: http://$(POD_IP):8093
          ports:
            - name: operations
              containerPort: 8082
            - name: node-internal
              containerPort: 8093
          livenessProbe:
            httpGet: { path: /healthz, port: operations }
            timeoutSeconds: 2
          readinessProbe:
            httpGet: { path: /readyz, port: operations }
            periodSeconds: 5
            timeoutSeconds: 2
            failureThreshold: 2
          startupProbe:
            httpGet: { path: /healthz, port: operations }
            periodSeconds: 2
            failureThreshold: 30
          resources:
            requests:
              cpu: 100m
              memory: 128Mi
            limits:
              cpu: "2"
              memory: 512Mi
          securityContext:
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities:
              drop: ["ALL"]
          volumeMounts:
            - name: objectstore
              mountPath: /var/lib/cchp/data/objectstore
            - name: task-results
              mountPath: /var/lib/cchp/data/task-results
            - name: scratch
              mountPath: /var/cache/cchp
      volumes:
        - name: objectstore
          persistentVolumeClaim:
            claimName: cchp-objectstore
        - name: task-results
          persistentVolumeClaim:
            claimName: cchp-task-results
        - name: scratch
          ephemeral:
            volumeClaimTemplate:
              spec:
                accessModes: ["ReadWriteOnce"]
                resources:
                  requests:
                    storage: 300Gi
```

入口。控制台域名转发到 control，API 域名只转发 `/v`、`/v1`、`/v1beta`、`/v4` 与 `/ws` 这几个路径：

```yaml filename="cchp-k3s/10-ingress.yaml"
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: cchp
  namespace: cchp
  annotations:
    nginx.ingress.kubernetes.io/proxy-read-timeout: "3600"
    nginx.ingress.kubernetes.io/proxy-send-timeout: "3600"
    nginx.ingress.kubernetes.io/proxy-body-size: "50m"
    nginx.ingress.kubernetes.io/proxy-buffering: "off"
spec:
  ingressClassName: nginx
  tls:
    - hosts:
        - api.cchp.example.com # API 域名
        - cchp.example.com # 控制台域名
      secretName: cchp-tls-cert
  rules:
    - host: api.cchp.example.com # API 域名
      http:
        paths:
          - path: /v
            pathType: Prefix
            backend: &gateway
              service:
                name: gateway
                port:
                  number: 8081
          - path: /v1
            pathType: Prefix
            backend: *gateway
          - path: /v1beta
            pathType: Prefix
            backend: *gateway
          - path: /v4
            pathType: Prefix
            backend: *gateway
          - path: /ws
            pathType: Prefix
            backend: *gateway
    - host: cchp.example.com # 控制台域名
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: control
                port:
                  number: 8080
---
# CC Hub 导出文件上传：不限制请求体大小，边接收边转发
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: cchp-cchub-import-upload
  namespace: cchp
  annotations:
    nginx.ingress.kubernetes.io/proxy-body-size: "0"
    nginx.ingress.kubernetes.io/proxy-request-buffering: "off"
    nginx.ingress.kubernetes.io/proxy-http-version: "1.1"
    nginx.ingress.kubernetes.io/proxy-read-timeout: "3600"
    nginx.ingress.kubernetes.io/proxy-send-timeout: "3600"
spec:
  ingressClassName: nginx
  tls:
    - hosts:
        - cchp.example.com # 控制台域名
      secretName: cchp-tls-cert
  rules:
    - host: cchp.example.com # 控制台域名
      http:
        paths:
          - path: /api/admin/cchub-import/upload
            pathType: Exact
            backend:
              service:
                name: control
                port:
                  number: 8080
```

## 第 2 步：填写域名与密钥

1. 把示例域名换成你的域名。先改前两行的两个变量，再执行：

   ```bash
   API_DOMAIN=api.cchp.example.com   # 你的 API 域名
   CONSOLE_DOMAIN=cchp.example.com   # 你的控制台域名
   sed -i -e "s/api\.cchp\.example\.com/$API_DOMAIN/g" -e "s/cchp\.example\.com/$CONSOLE_DOMAIN/g" cchp-k3s/*.yaml
   grep -n -e "$API_DOMAIN" -e "$CONSOLE_DOMAIN" cchp-k3s/*.yaml
   ```

   结果：列出 `02-config.yaml` 中的 3 行与 `10-ingress.yaml` 中的 6 行，都是你的域名。

2. 为每个占位值生成一个随机值：

   ```bash
   for name in OWNER_PASSWORD RUNTIME_PASSWORD TOKEN_PEPPER MASTER_KEY DRAGONFLY_KEY_SECRET; do
     sed -i "s/CHANGE_ME_$name/$(openssl rand -hex 32)/g" cchp-k3s/01-secrets.yaml
   done
   grep -n CHANGE_ME cchp-k3s/01-secrets.yaml
   ```

   结果：`grep` 没有任何输出。同一个占位值出现在两处时，两处会换成同一个值。

> [!WARNING]
>
> **警告**：`01-secrets.yaml` 中的 `CCH_MASTER_KEY` 是主加密密钥，丢失或更换后，已加密保存的数据无法解密。把这个文件备份到安全的位置。第一次部署之后不要重新生成其中的值：数据库密码只在第一次启动 PostgreSQL 时写入。

始终用控制台域名打开控制台。登录 Cookie、跨站请求检查、通行密钥和第三方登录的回调地址都绑定 `CCH_PUBLIC_BASE_URL`。只在内网测试时，可以打开降低安全性部署，用 http 地址与内网主机名运行，见 [降低安全性部署（内网测试）](https://cch-plus.com/zh-CN/docs/installation/lan-testing)。

## 第 3 步：部署

创建命名空间与 TLS 证书的 Secret，再应用全部文件。把 `fullchain.pem` 与 `privkey.pem` 换成你的证书与私钥文件：

```bash
kubectl apply -f cchp-k3s/00-namespace.yaml
kubectl -n cchp create secret tls cchp-tls-cert --cert=fullchain.pem --key=privkey.pem
kubectl apply -f cchp-k3s/
```

用 cert-manager 签发证书时，不执行第二条命令，改为在 `10-ingress.yaml` 中 `cchp` 这个 Ingress 的 `annotations` 下加入 `cert-manager.io/cluster-issuer: <你的 ClusterIssuer 名称>`。另一个 Ingress 复用同一个证书。

结果：kubectl 逐行列出创建的资源。PostgreSQL 就绪之前，迁移 Job 会失败并自动重试几次，这是正常现象。control、gateway 和 worker 的 Pod 停在初始化容器 `wait-for-migrations`，直到迁移完成。

## 第 4 步：确认服务就绪

```bash
kubectl -n cchp wait --for=condition=complete job/cchp-migrate --timeout=864m
kubectl -n cchp get pods
kubectl get --raw /api/v1/namespaces/cchp/services/gateway:8081/proxy/readyz
curl -s https://cchp.example.com/readyz
```

`--timeout` 与迁移 Job 的最长运行时间相同。全新安装的迁移通常几分钟内完成。

结果：

- 第一条命令输出 `job.batch/cchp-migrate condition met`。
- `control`、`gateway-0`、`worker`、`postgres-0`、`dragonfly-0` 的 Pod 都是 `Running` 且 `READY` 为 `1/1`。迁移 Job 最新的 Pod 为 `Completed`，PostgreSQL 就绪前失败的 Pod 显示 `Error`。
- 两个 `/readyz` 请求都返回 `"status":"ready"`：前一个直接检查 gateway，后一个经过 Ingress 与 TLS 检查 control。

## 第 5 步：完成安装向导

1. 从 control 的日志中取出一次性安装令牌：

   ```bash
   kubectl -n cchp logs deploy/control | grep 'CCHP setup token'
   ```

   结果：输出一行 `CCHP setup token: cchp_setup_...`。日志中找不到时，见「常见问题」中的「日志中找不到安装令牌」。

2. 在浏览器中打开 `https://cchp.example.com`。在 **输入安装令牌** 页面，把令牌粘贴到 **安装令牌**，点击 **验证并继续**。

3. 按顺序完成 **站点**、**管理员**、**两步验证**、**邮件服务**、**登录方式**、**数据库**、**组织**、**访客 IP** (since v1.0.15) 八个步骤。**两步验证** 与 **邮件服务** 可以跳过。各步骤的填写方法见 Docker Compose 安装的 [第 7 步：完成安装向导](https://cch-plus.com/zh-CN/docs/installation/docker-compose#setup-wizard)，三种安装方式相同。

   - **站点**：**公开访问地址** 显示 `https://cchp.example.com`。
   - **数据库**（页面标题为 **检查数据库可观测性**）：迁移 Job 已为内置的 PostgreSQL 完成授权，页面显示 **数据库可观测性已就绪。**，点击 **继续**。
   - **组织**：填写 **组织名称** 与 **团队名称**，在 **组织类型** 中选择 **预付费** 或 **后付费**，点击 **创建并继续**。创建首个组织即完成安装。

结果：浏览器进入控制台。此时还没有供应商，网关对代理请求返回无路由错误。后面的章节介绍如何创建供应商与 LLM 密钥。

## 查看日志

```bash
kubectl -n cchp logs deploy/control -f
kubectl -n cchp logs statefulset/gateway -f
kubectl -n cchp logs deploy/worker -f
kubectl -n cchp logs job/cchp-migrate
```

迁移 Job 完成 1 小时后被自动删除，它的日志也随之删除。control、gateway、worker 分别在 Pod 的 8085、8084、8082 端口的 `/metrics` 提供 Prometheus 指标，需要监控时按 Pod 抓取。

## 备份

| 内容 | 位置 | 建议 |
| - | - | - |
| 密钥 | `cchp-k3s/01-secrets.yaml` | 必须备份。主加密密钥与令牌哈希密钥只保存在这里和集群的 Secret 中 |
| 数据库 | 卷 `data-postgres-0` | 必须备份，用 `pg_dump` 导出 |
| 请求归档等节点数据 | 卷 `archive-gateway-0` | 与数据库分开备份 |
| 共享数据 | 卷 `cchp-objectstore`、`cchp-task-results` | 插件包、导出文件、审计归档、CC Hub 上传文件与任务结果文件 |

local-path 的卷是节点上 `/var/lib/rancher/k3s/storage/` 下以卷名结尾的目录。

导出数据库：

```bash
kubectl -n cchp exec postgres-0 -- pg_dump -U hub -d app -Fc > cchp-$(date +%F).dump
```

结果：当前目录生成 `cchp-` 加日期命名的备份文件。`pg_dump` 提示 `circular foreign-key constraints` 时可以忽略，这是 TimescaleDB 内部表的提示。恢复方法见「退回旧版本」。

## 升级

`latest` 是最新的正式版本。升级前先按「备份」导出数据库。

```bash
k3s crictl pull ghcr.io/cch-hq/cch-plus:latest
kubectl -n cchp scale deployment/control deployment/worker --replicas=0
kubectl -n cchp delete job cchp-migrate --ignore-not-found
for f in cchp-k3s/0[0-6]-*.yaml; do kubectl apply -f "$f"; done
kubectl -n cchp wait --for=condition=complete job/cchp-migrate --timeout=864m
kubectl apply -f cchp-k3s/09-worker.yaml
kubectl -n cchp rollout status deployment/worker
kubectl apply -f cchp-k3s/
kubectl -n cchp rollout restart statefulset/gateway
kubectl -n cchp rollout status deployment/control
kubectl -n cchp rollout status statefulset/gateway
```

各命令的作用：

1. 清单中的 CCHP 镜像只在节点上没有时才拉取（`imagePullPolicy: IfNotPresent`），重启 Pod 不会意外换成新版本。所以先用 `k3s crictl pull` 取得新的 `latest`。
2. 停止 control 与 worker，并删除上一次的迁移 Job：Job 不能修改，完成后也不会重新运行。
3. 应用 `00` 到 `06` 号文件，只用新版本运行迁移。这期间 gateway 继续用旧版本处理请求。
4. 迁移完成后先启动新版本的 worker，再应用全部文件，启动 control 并重启 gateway。gateway 停止前最多等待 900 秒让进行中的请求结束，最后一步可能需要十几分钟。

结果：**系统管理** → **关于** 的 **当前版本** 显示新版本号。从停止 control 到它重新就绪之前，控制台不可用。

新版本的清单文件有变化时，先按本页更新 `cchp-k3s/` 中的文件，再执行上面的命令。

要运行指定版本，把文件中的 `latest` 换成版本号，例如 `1.0.11`，然后执行上面除第一条以外的命令。节点上没有这个版本时，Pod 启动时会自动拉取：

```bash
sed -i 's/cch-plus:[^ ]*/cch-plus:1.0.11/' cchp-k3s/*.yaml
```

### 退回旧版本

迁移只能向前执行，只换回旧镜像不能撤销新版本对数据库的修改，旧版本的 `wait-for-migrations` 可能报错退出。退回时用升级前的备份重建数据库：

```bash
kubectl -n cchp scale deployment/control deployment/worker statefulset/gateway --replicas=0
sed -i 's/cch-plus:[^ ]*/cch-plus:1.0.11/' cchp-k3s/*.yaml
kubectl -n cchp exec postgres-0 -- psql -U hub -d postgres -c 'DROP DATABASE app WITH (FORCE)' -c 'CREATE DATABASE app'
kubectl -n cchp exec postgres-0 -- psql -U hub -d app -c 'CREATE EXTENSION IF NOT EXISTS timescaledb' -c 'SELECT timescaledb_pre_restore()'
kubectl -n cchp exec -i postgres-0 -- pg_restore -U hub -d app < cchp-YYYY-MM-DD.dump
kubectl -n cchp exec postgres-0 -- psql -U hub -d app -c 'SELECT timescaledb_post_restore()'
kubectl -n cchp delete job cchp-migrate --ignore-not-found
kubectl apply -f cchp-k3s/
```

把 `1.0.11` 换成备份时运行的版本号，把文件名换成你的备份文件。`timescaledb_pre_restore()` 与 `timescaledb_post_restore()` 是 TimescaleDB 要求的恢复前后步骤。

结果：`pg_restore` 没有输出错误；迁移 Job 确认这个版本的迁移都已执行，control、gateway 与 worker 恢复服务。

## 卸载

> [!WARNING]
>
> **警告**：删除命名空间 `cchp` 会同时删除其中的全部 Secret 与卷。local-path 的回收策略为 `Delete`，数据库、请求归档与上传文件会被永久删除。卸载前先按「备份」导出数据库，并保留 `01-secrets.yaml`。

```bash
kubectl delete namespace cchp
```

结果：`kubectl get namespace cchp` 提示找不到该命名空间。入口控制器与 k3s 本身不受影响。

## 常见问题

### Pod 一直停在 Init:0/1

control、gateway 和 worker 在迁移完成之前停在初始化容器 `wait-for-migrations`。用 `kubectl -n cchp get job cchp-migrate` 与 `kubectl -n cchp logs job/cchp-migrate` 查看迁移 Job。日志提示 `password authentication failed` 时，`01-secrets.yaml` 中的数据库密码在第一次部署之后被重新生成过，请换回原来的文件。修正后执行 `kubectl -n cchp delete job cchp-migrate` 与 `kubectl apply -f cchp-k3s/`。

### 进程启动后立即退出

用 `kubectl -n cchp logs deploy/control --previous` 查看上一次启动的日志。提示 `CCH_MASTER_KEY hex decode` 时，`01-secrets.yaml` 中还有没替换的占位值，按第 2 步替换后执行 `kubectl apply -f cchp-k3s/01-secrets.yaml` 与 `kubectl -n cchp rollout restart deployment/control deployment/worker statefulset/gateway`。

### 安装向导提示 **当前打开的地址不一致**

浏览器打开的地址与 `CCH_PUBLIC_BASE_URL` 不同。打开 `02-config.yaml` 中的控制台地址；或者修改这个文件后执行 `kubectl apply -f cchp-k3s/02-config.yaml` 与 `kubectl -n cchp rollout restart deployment/control deployment/worker statefulset/gateway`。

### 日志中找不到安装令牌

输出当前的令牌：

```bash
kubectl -n cchp exec deploy/control -- gateway identity setup-token
```

令牌已经用过但安装没有完成时，执行 `kubectl -n cchp rollout restart deployment/control`，control 会在日志中输出新的令牌。已经创建管理员后，命令报错 `installation already has users`，请直接登录。

### 域名打不开，或返回 404

确认 Traefik 已关闭，并且 ingress-nginx 正在运行：`kubectl get ingressclass` 的输出中应有 `nginx`。k3s 自带的 Traefik 不处理 `ingressClassName` 为 `nginx` 的 Ingress。

## 相关页面

- [安装概览](https://cch-plus.com/zh-CN/docs/installation)
- [Docker Compose 安装](https://cch-plus.com/zh-CN/docs/installation/docker-compose)：安装向导的各个步骤，以及 [高可用、对象存储与性能调优](https://cch-plus.com/zh-CN/docs/installation/docker-compose#ha-ops)（S3 默认对象存储、`gateway objectstore copy`、主库切换容错、定时 PGO 与 `ledger_reconcile`）(since v1.0.15)
- [二进制安装](https://cch-plus.com/zh-CN/docs/installation/binary)
