# k3s / k8s 安裝

Source: https://cch-plus.com/zh-TW/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-TW/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-TW/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-TW/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-TW/docs/installation)
- [Docker Compose 安裝](https://cch-plus.com/zh-TW/docs/installation/docker-compose)：安裝精靈的各個步驟，以及 [高可用、物件儲存與效能調校](https://cch-plus.com/zh-TW/docs/installation/docker-compose#ha-ops)（S3 預設物件儲存、`gateway objectstore copy`、主庫切換容錯、排程 PGO 與 `ledger_reconcile`）(since v1.0.15)
- [二進位安裝](https://cch-plus.com/zh-TW/docs/installation/binary)
