範例:使用 StatefulSet 部署 Cassandra

本教學課程示範如何在 Kubernetes 上執行 Apache Cassandra。Cassandra 是一個資料庫,需要持久性儲存來提供資料持久性(應用程式狀態)。在本範例中,自訂 Cassandra Seed 提供者讓資料庫能夠在新的 Cassandra 執行個體加入 Cassandra 叢集時探索它們。

StatefulSets 讓您更輕鬆地將有狀態應用程式部署到 Kubernetes 叢集中。如需本教學課程中使用的功能的詳細資訊,請參閱 StatefulSet

目標

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

準備開始

您需要有一個 Kubernetes 叢集,並且必須設定 kubectl 命令列工具以與您的叢集通訊。建議在至少有兩個節點且未充當控制平面主機的叢集上執行本教學課程。如果您還沒有叢集,可以使用 minikube 建立一個,或者您可以使用以下 Kubernetes Playground 之一

要完成本教學課程,您應該已經基本熟悉 Pod服務StatefulSet

其他 Minikube 設定說明

為 Cassandra 建立無頭服務

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

以下服務用於 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 檔案建立服務以追蹤所有 Cassandra StatefulSet 成員

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

驗證(選用)

取得 Cassandra 服務。

kubectl get svc cassandra

回應為

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

如果您沒有看到名為 cassandra 的服務,則表示建立失敗。請閱讀 偵錯服務 以取得疑難排解常見問題的協助。

使用 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 設定的服務

    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:Use code_sample shortcode instead of code shortcode (e8b136c3b3)