# k3s / k8s로 설치하기

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

> 매니페스트 파일 11개로 k3s 노드 1대에 CCHP를 배포합니다. 파일 저장, 도메인과 키 입력, 배포와 설치 마법사 완료, 그리고 백업, 업그레이드, 제거 방법을 설명합니다.

이 페이지는 k3s 노드 1대에 CCHP를 배포합니다. Docker Compose는 컨테이너 1개에서 모든 역할을 실행하지만, 여기서는 control(콘솔과 관리 API), gateway(LLM 게이트웨이), worker(백그라운드 작업)가 각각 독립된 워크로드입니다. 각 워크로드는 자체 리소스 상한, 헬스 체크, 로그를 가지며 개별적으로 다시 시작할 수 있습니다. 데이터베이스는 같은 노드의 단일 인스턴스 PostgreSQL 18(TimescaleDB 포함)과 Dragonfly를 사용합니다. 이미 k3s로 서버를 관리하고 있거나 역할별로 리소스를 제한하려면 이 페이지를 선택하세요. 그렇지 않으면 [Docker Compose로 설치하기](https://cch-plus.com/ko/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[업스트림 프로바이더]
```

## 시작하기 전에

- k3s가 설치되어 있고 k3s에 기본 포함된 Traefik이 꺼져 있는 Linux 서버 1대(amd64 또는 arm64). 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가 모두 이 서버를 가리키는 도메인 2개: 콘솔 도메인(이 페이지에서는 `cchp.example.com`)과 API 도메인(이 페이지에서는 `api.cchp.example.com`). 그리고 두 도메인을 모두 포함하는 TLS 인증서와 개인 키 1세트.

- 메모리: 각 워크로드의 메모리 상한은 합계 5 GiB입니다. 이와 별도로 k3s와 인그레스 컨트롤러 자체가 사용할 메모리를 남겨 두어야 합니다.

- 디스크: k3s에 기본 포함된 local-path 스토리지는 볼륨 용량을 제한하지 않으며, 모든 볼륨이 노드 디스크를 함께 사용합니다. 매니페스트의 볼륨 클레임은 합계 약 481 GiB이므로 노드 디스크는 이 값 이상을 권장합니다.

- 서버에서 `ghcr.io`, Docker Hub, `docker.dragonflydb.io`, `cch-plus.com`(모델 가격표)에 접근할 수 있어야 합니다.

이 페이지의 명령은 모두 이 서버에서 root 사용자로 실행합니다. `kubectl`은 k3s에 포함되어 있습니다.

## 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
```

공유 설정입니다. 주소 3개는 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가 함께 사용하는 볼륨 2개:

```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. 예시 도메인을 자신의 도메인으로 바꾸세요. 먼저 처음 두 줄의 변수 2개를 수정한 다음 실행하세요.

   ```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을 처음 시작할 때만 기록됩니다.

콘솔은 항상 콘솔 도메인으로 여세요. 로그인 쿠키, 교차 사이트 요청 검사, 패스키, 서드 파티 로그인의 콜백 주소는 모두 `CCH_PUBLIC_BASE_URL`에 바인딩됩니다. LAN 테스트용으로만 쓸 때는 보안을 낮춘 배포를 켜고 http 주소와 내부망 호스트 이름으로 실행할 수 있습니다. [보안을 낮춘 배포(LAN 테스트용)](https://cch-plus.com/ko/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`을 여세요. **Enter the setup token** 페이지에서 토큰을 **Setup token** 필드에 붙여 넣고 **Verify and continue** 버튼을 선택하세요.

3. **Site**, **Administrator**, **Two-step**, **Email**, **Sign-in**, **Database**, **Organization**, **Visitor IP** (since v1.0.15) 8개 단계를 순서대로 완료하세요. **Two-step** 단계와 **Email** 단계는 건너뛸 수 있습니다. 각 단계의 입력 방법은 Docker Compose로 설치하기의 [7단계: 설치 마법사 완료하기](https://cch-plus.com/ko/docs/installation/docker-compose#setup-wizard)를 참조하세요. 세 가지 설치 방법 모두 같습니다.

   - **Site**: **Public URL** 필드에 `https://cchp.example.com`이 표시됩니다.
   - **Database**(페이지 제목은 **Check database observability**): 마이그레이션 Job이 내장 PostgreSQL에 대한 권한 부여를 이미 완료했으므로 페이지에 **Database observability is ready.** 메시지가 표시됩니다. **Continue** 버튼을 선택하세요.
   - **Organization**: **Organization name** 필드와 **Team name** 필드를 입력하고 **Organization type**에서 **Prepaid** 또는 **Postpaid**를 선택한 뒤 **Create and continue** 버튼을 선택하세요. 첫 번째 조직을 만들면 설치가 완료됩니다.

결과: 브라우저에 콘솔이 열립니다. 아직 프로바이더가 없으므로 게이트웨이는 프록시 요청에 라우팅 없음 오류를 반환합니다. 프로바이더와 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초 기다리므로 마지막 단계는 10여 분이 걸릴 수 있습니다.

결과: **System Management** → **About** 페이지의 **Current version** 항목에 새 버전 번호가 표시됩니다. 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`를 실행하세요.

### 설치 마법사에 ‘You opened a different address’ 메시지가 표시되나요?

브라우저에서 연 주소가 `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/ko/docs/installation)
- [Docker Compose로 설치하기](https://cch-plus.com/ko/docs/installation/docker-compose): 설치 마법사의 각 단계 및 [고가용성, 오브젝트 스토리지 및 성능 튜닝](https://cch-plus.com/ko/docs/installation/docker-compose#ha-ops)(S3 기본 오브젝트 스토리지, `gateway objectstore copy`, 프라이머리 페일오버 내성, 정기 PGO 및 `ledger_reconcile`) (since v1.0.15)
- [바이너리로 설치하기](https://cch-plus.com/ko/docs/installation/binary)
