示例:使用 StatefulSet 部署 Cassandra

本教程演示如何在 Kubernetes 上執行 Apache Cassandra。Cassandra 是一個數據庫,需要持久儲存來提供資料永續性(應用程式**狀態**)。在本示例中,自定義 Cassandra 種子提供程式使資料庫能夠發現加入 Cassandra 叢集的新 Cassandra 例項。

**StatefulSet** 使在 Kubernetes 叢集中部署有狀態應用程式變得更加容易。有關本教程中使用的功能的更多資訊,請參閱 StatefulSet

目標

  • 建立並驗證 Cassandra 無頭 Service
  • 使用 StatefulSet 建立 Cassandra 環。
  • 驗證 StatefulSet。
  • 修改 StatefulSet。
  • 刪除 StatefulSet 及其 Pod

準備工作

你需要擁有一個 Kubernetes 叢集,並且 kubectl 命令列工具已配置為與你的叢集通訊。建議在本教程中使用至少兩個不充當控制平面主機的節點組成的叢集。如果你還沒有叢集,可以使用 minikube 建立一個,或者使用以下某個 Kubernetes 試驗環境。

要完成本教程,你應對 PodServiceStatefulSet 有基本的瞭解。

Minikube 額外設定說明

為 Cassandra 建立無頭 Service

在 Kubernetes 中,Service 描述了一組執行相同任務的 Pod

以下 Service 用於 Cassandra Pod 和叢集內客戶端之間的 DNS 查詢:

apiVersion: v1
kind: Service
metadata:
  labels:
    app: cassandra
  name: cassandra
spec:
  clusterIP: None
  ports:
  - port: 9042
  selector:
    app: cassandra

cassandra-service.yaml 檔案建立 Service 以跟蹤所有 Cassandra StatefulSet 成員。

kubectl apply -f https://k8s.io/examples/application/cassandra/cassandra-service.yaml

驗證(可選)

獲取 Cassandra Service。

kubectl get svc cassandra

響應為:

NAME        TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)    AGE
cassandra   ClusterIP   None         <none>        9042/TCP   45s

如果你沒有看到名為 cassandra 的 Service,則表示建立失敗。請閱讀 除錯服務 以獲取常見問題的故障排除幫助。

使用 StatefulSet 建立 Cassandra 環

下面包含的 StatefulSet 清單建立了一個由三個 Pod 組成的 Cassandra 環。

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: cassandra
  labels:
    app: cassandra
spec:
  serviceName: cassandra
  replicas: 3
  selector:
    matchLabels:
      app: cassandra
  template:
    metadata:
      labels:
        app: cassandra
    spec:
      terminationGracePeriodSeconds: 500
      containers:
      - name: cassandra
        image: gcr.io/google-samples/cassandra:v13
        imagePullPolicy: Always
        ports:
        - containerPort: 7000
          name: intra-node
        - containerPort: 7001
          name: tls-intra-node
        - containerPort: 7199
          name: jmx
        - containerPort: 9042
          name: cql
        resources:
          limits:
            cpu: "500m"
            memory: 1Gi
          requests:
            cpu: "500m"
            memory: 1Gi
        securityContext:
          capabilities:
            add:
              - IPC_LOCK
        lifecycle:
          preStop:
            exec:
              command: 
              - /bin/sh
              - -c
              - nodetool drain
        env:
          - name: MAX_HEAP_SIZE
            value: 512M
          - name: HEAP_NEWSIZE
            value: 100M
          - name: CASSANDRA_SEEDS
            value: "cassandra-0.cassandra.default.svc.cluster.local"
          - name: CASSANDRA_CLUSTER_NAME
            value: "K8Demo"
          - name: CASSANDRA_DC
            value: "DC1-K8Demo"
          - name: CASSANDRA_RACK
            value: "Rack1-K8Demo"
          - name: POD_IP
            valueFrom:
              fieldRef:
                fieldPath: status.podIP
        readinessProbe:
          exec:
            command:
            - /bin/bash
            - -c
            - /ready-probe.sh
          initialDelaySeconds: 15
          timeoutSeconds: 5
        # These volume mounts are persistent. They are like inline claims,
        # but not exactly because the names need to match exactly one of
        # the stateful pod volumes.
        volumeMounts:
        - name: cassandra-data
          mountPath: /cassandra_data
  # These are converted to volume claims by the controller
  # and mounted at the paths mentioned above.
  # do not use these in production until ssd GCEPersistentDisk or other ssd pd
  volumeClaimTemplates:
  - metadata:
      name: cassandra-data
    spec:
      accessModes: [ "ReadWriteOnce" ]
      storageClassName: fast
      resources:
        requests:
          storage: 1Gi
---
kind: StorageClass
apiVersion: storage.k8s.io/v1
metadata:
  name: fast
provisioner: k8s.io/minikube-hostpath
parameters:
  type: pd-ssd

cassandra-statefulset.yaml 檔案建立 Cassandra StatefulSet。

# Use this if you are able to apply cassandra-statefulset.yaml unmodified
kubectl apply -f https://k8s.io/examples/application/cassandra/cassandra-statefulset.yaml

如果需要修改 cassandra-statefulset.yaml 以適應你的叢集,請下載 https://k8s.io/examples/application/cassandra/cassandra-statefulset.yaml,然後從你儲存修改版本所在的資料夾應用該清單:

# Use this if you needed to modify cassandra-statefulset.yaml locally
kubectl apply -f cassandra-statefulset.yaml

驗證 Cassandra StatefulSet

  1. 獲取 Cassandra StatefulSet

    kubectl get statefulset cassandra
    

    響應應類似於:

    NAME        DESIRED   CURRENT   AGE
    cassandra   3         0         13s
    

    `StatefulSet` 資源按順序部署 Pod。

  2. 獲取 Pod 以檢視按序建立的狀態。

    kubectl get pods -l="app=cassandra"
    

    響應應類似於:

    NAME          READY     STATUS              RESTARTS   AGE
    cassandra-0   1/1       Running             0          1m
    cassandra-1   0/1       ContainerCreating   0          8s
    

    所有三個 Pod 可能需要幾分鐘才能部署完成。部署完成後,相同的命令會返回類似於以下內容的輸出:

    NAME          READY     STATUS    RESTARTS   AGE
    cassandra-0   1/1       Running   0          10m
    cassandra-1   1/1       Running   0          9m
    cassandra-2   1/1       Running   0          8m
    
  3. 在第一個 Pod 中執行 Cassandra nodetool,以顯示環的狀態。

    kubectl exec -it cassandra-0 -- nodetool status
    

    響應應類似於:

    Datacenter: DC1-K8Demo
    ======================
    Status=Up/Down
    |/ State=Normal/Leaving/Joining/Moving
    --  Address     Load       Tokens       Owns (effective)  Host ID                               Rack
    UN  172.17.0.5  83.57 KiB  32           74.0%             e2dd09e6-d9d3-477e-96c5-45094c08db0f  Rack1-K8Demo
    UN  172.17.0.4  101.04 KiB  32           58.8%             f89d6835-3a42-4419-92b3-0e62cae1479c  Rack1-K8Demo
    UN  172.17.0.6  84.74 KiB  32           67.1%             a6a1e8c2-3dc5-4417-b1a0-26507af2aaad  Rack1-K8Demo
    

修改 Cassandra StatefulSet

使用 `kubectl edit` 修改 Cassandra StatefulSet 的大小。

  1. 執行以下命令:

    kubectl edit statefulset cassandra
    

    此命令會在你的終端中開啟一個編輯器。你需要更改的行是 `replicas` 欄位。以下示例是 StatefulSet 檔案的摘錄:

    # Please edit the object below. Lines beginning with a '#' will be ignored,
    # and an empty file will abort the edit. If an error occurs while saving this file will be
    # reopened with the relevant failures.
    #
    apiVersion: apps/v1
    kind: StatefulSet
    metadata:
      creationTimestamp: 2016-08-13T18:40:58Z
      generation: 1
      labels:
      app: cassandra
      name: cassandra
      namespace: default
      resourceVersion: "323"
      uid: 7a219483-6185-11e6-a910-42010a8a0fc0
    spec:
      replicas: 3
    
  2. 將副本數量更改為 4,然後儲存清單。

    StatefulSet 現在將擴容以執行 4 個 Pod。

  3. 獲取 Cassandra StatefulSet 以驗證你的更改。

    kubectl get statefulset cassandra
    

    響應應類似於:

    NAME        DESIRED   CURRENT   AGE
    cassandra   4         4         36m
    

清理

刪除或縮減 StatefulSet 不會刪除與 StatefulSet 相關聯的卷。此設定是為了你的安全,因為你的資料比自動清除所有相關的 StatefulSet 資源更有價值。

  1. 執行以下命令(連結成一個命令)以刪除 Cassandra StatefulSet 中的所有內容:

    grace=$(kubectl get pod cassandra-0 -o=jsonpath='{.spec.terminationGracePeriodSeconds}') \
      && kubectl delete statefulset -l app=cassandra \
      && echo "Sleeping ${grace} seconds" 1>&2 \
      && sleep $grace \
      && kubectl delete persistentvolumeclaim -l app=cassandra
    
  2. 執行以下命令以刪除為 Cassandra 設定的 Service:

    kubectl delete service -l app=cassandra
    

Cassandra 容器環境變數

本教程中的 Pod 使用 Google 容器登錄檔中的 `gcr.io/google-samples/cassandra:v13` 映象。上述 Docker 映象基於 debian-base 幷包含 OpenJDK 8。

此映象包含來自 Apache Debian 倉庫的標準 Cassandra 安裝。透過使用環境變數,你可以更改插入到 `cassandra.yaml` 中的值。

環境變數預設值
CASSANDRA_CLUSTER_NAME'Test Cluster'
CASSANDRA_NUM_TOKENS32
CASSANDRA_RPC_ADDRESS0.0.0.0

下一步

最後修改於 2023 年 8 月 24 日下午 6:38 PST:使用 code_sample 簡碼代替 code 簡碼 (e8b136c3b3)