在 GKE 上部署 Elasticsearch 向量資料庫


本教學課程說明如何在 Google Kubernetes Engine (GKE) 上部署 Elasticsearch 向量資料庫叢集。

向量資料庫 是專門設計的資料儲存庫,用於管理及搜尋大量高維度向量。這些向量代表文字、圖片、音訊、影片或任何可編碼為數值的資料。與依賴完全比對的關聯式資料庫不同,向量資料庫專門用於尋找相似項目,或識別大型資料集內的模式。

Elasticsearch 是一種向量資料庫,結合了搜尋和分析功能。這項服務提供開放式 REST API,可管理叢集,並支援結構化查詢、全文查詢和複雜查詢。Elasticsearch 可讓您執行詞組、相似度和前置字元搜尋,並提供自動完成建議。

本教學課程適用於有興趣在 GKE 上部署 Elasticsearch 資料庫叢集的雲端平台管理員和架構師機器學習工程師,以及 MLOps (開發運作) 專業人員。

優點

Elasticsearch 具有下列優點:

  • 提供各種程式設計語言的程式庫和開放式 API,可與其他服務整合。
  • 支援水平擴充、分片和複製,可簡化擴充和高可用性。
  • 多節點叢集平衡,可達到最佳資源使用率。
  • 支援容器和 Kubernetes,可順暢整合至現代雲端原生環境。

目標

在本教學課程中,您將瞭解以下內容:

  • 規劃及部署 Elasticsearch 的 GKE 基礎架構。
  • 在 GKE 叢集中部署及設定 Elasticsearch。
  • 部署 StatefulHA 運算子,確保 Elasticsearch 高可用性。
  • 執行筆記本,在資料庫中生成及儲存範例向量嵌入,並執行以向量為準的搜尋查詢。
  • 在資訊主頁上收集指標並以視覺化方式呈現。

部署架構

在本教學課程中,您將部署 Elasticsearch 的高可用性區域 GKE 叢集,其中多個 Kubernetes 節點會分散在多個可用區。這項設定有助於確保容錯能力、擴充性和地理位置備援。這項功能可讓您進行輪流更新和維護作業,同時提供運作時間和可用性的服務水準協議。詳情請參閱區域叢集

節點無法連線時,系統不會立即重新排定該節點上的 Pod。如果 Pod 使用 StatefulSet,應用程式 Pod 可能需要超過八分鐘的時間才能刪除,並重新排程至新節點。

為解決這個問題,StatefulHA 運算子會執行下列操作:

  • 使用 .forceDeleteStrategy: AfterNodeUnreachable 設定解決重新排程延遲問題、處理容錯移轉設定,並縮短復原時間。
  • 確保 StatefulSet 應用程式使用 RePD。
  • 使用自訂 HighAvailabilityApplication 資源擴充 GKE,該資源會部署在與 Elasticsearch 相同的命名空間中。這可讓 StatefulHA 運算子監控容錯移轉事件並做出回應。

下圖顯示在 GKE 叢集的多個節點和區域中執行的 Elasticsearch 叢集:

Elasticsearch 部署架構

費用

在本文件中,您會使用 Google Cloud的下列計費元件:

如要根據預測用量估算費用,請使用 Pricing Calculator

初次使用 Google Cloud 的使用者可能符合免費試用資格。

完成本文所述工作後,您可以刪除已建立的資源,避免繼續計費。詳情請參閱清除所用資源一節。

根據伺服器端公眾授權 (SSPL),Elasticsearch 可免費使用。

事前準備

在本教學課程中,您將使用 Cloud Shell 執行指令。Cloud Shell 是殼層環境,用於管理 Google Cloud上託管的資源。這個環境已預先安裝 Google Cloud CLIkubectlHelm Terraform 指令列工具。如果您未使用 Cloud Shell,則必須安裝 Google Cloud CLI。

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. Install the Google Cloud CLI.

  3. 如果您使用外部識別資訊提供者 (IdP),請先 使用聯合身分登入 gcloud CLI

  4. 如要初始化 gcloud CLI,請執行下列指令:

    gcloud init
  5. Create or select a Google Cloud project.

    • Create a Google Cloud project:

      gcloud projects create PROJECT_ID

      Replace PROJECT_ID with a name for the Google Cloud project you are creating.

    • Select the Google Cloud project that you created:

      gcloud config set project PROJECT_ID

      Replace PROJECT_ID with your Google Cloud project name.

  6. Verify that billing is enabled for your Google Cloud project.

  7. Enable the Cloud Resource Manager, Compute Engine, GKE, IAM Service Account Credentials, and Backup for GKE APIs:

    gcloud services enable cloudresourcemanager.googleapis.com compute.googleapis.com container.googleapis.com iamcredentials.googleapis.com gkebackup.googleapis.com
  8. Install the Google Cloud CLI.

  9. 如果您使用外部識別資訊提供者 (IdP),請先 使用聯合身分登入 gcloud CLI

  10. 如要初始化 gcloud CLI,請執行下列指令:

    gcloud init
  11. Create or select a Google Cloud project.

    • Create a Google Cloud project:

      gcloud projects create PROJECT_ID

      Replace PROJECT_ID with a name for the Google Cloud project you are creating.

    • Select the Google Cloud project that you created:

      gcloud config set project PROJECT_ID

      Replace PROJECT_ID with your Google Cloud project name.

  12. Verify that billing is enabled for your Google Cloud project.

  13. Enable the Cloud Resource Manager, Compute Engine, GKE, IAM Service Account Credentials, and Backup for GKE APIs:

    gcloud services enable cloudresourcemanager.googleapis.com compute.googleapis.com container.googleapis.com iamcredentials.googleapis.com gkebackup.googleapis.com
  14. Grant roles to your user account. Run the following command once for each of the following IAM roles: roles/storage.objectViewer, roles/container.admin, roles/iam.serviceAccountAdmin, roles/compute.admin, roles/gkebackup.admin, roles/monitoring.viewer

    gcloud projects add-iam-policy-binding PROJECT_ID --member="user:USER_IDENTIFIER" --role=ROLE

    Replace the following:

    • PROJECT_ID: your project ID.
    • USER_IDENTIFIER: the identifier for your user account—for example, myemail@example.com.
    • ROLE: the IAM role that you grant to your user account.
  15. 設定環境

    如要使用 Cloud Shell 設定環境,請按照下列步驟操作:

    1. 為專案、區域和 Kubernetes 叢集資源前置字串設定環境變數:

      export PROJECT_ID=PROJECT_ID
      export KUBERNETES_CLUSTER_PREFIX=elasticsearch
      export REGION=us-central1
      
      • PROJECT_ID 替換為專案 ID。 Google Cloud

      本教學課程使用 us-central1 地區建立部署資源。

    2. 檢查 Helm 版本:

      helm version
      

      如果版本舊於 3.13,請更新版本:

      curl https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3 | bash
      
    3. 從 GitHub 複製程式碼範例存放區:

      git clone https://github.com/GoogleCloudPlatform/kubernetes-engine-samples
      
    4. 前往 elasticsearch 目錄,開始建立部署資源:

      cd kubernetes-engine-samples/databases/elasticsearch
      

    建立叢集基礎架構

    在本節中,您將執行 Terraform 指令碼,建立私人、高可用性的區域 GKE 叢集,以部署 Elasticsearch 資料庫。

    您可以選擇使用標準或 Autopilot 叢集部署 Elasticsearch。每種方式各有優勢,計費模式也不同。

    Autopilot

    下圖顯示部署在專案中的 Autopilot GKE 叢集。

    GKE Autopilot 叢集

    如要部署叢集基礎架構,請在 Cloud Shell 中執行下列指令:

    export GOOGLE_OAUTH_ACCESS_TOKEN=$(gcloud auth print-access-token)
    terraform -chdir=terraform/gke-autopilot init
    terraform -chdir=terraform/gke-autopilot apply \
    -var project_id=${PROJECT_ID} \
    -var region=${REGION} \
    -var cluster_prefix=${KUBERNETES_CLUSTER_PREFIX}
    

    GKE 會在執行階段替換下列變數:

    • GOOGLE_OAUTH_ACCESS_TOKEN 會使用 gcloud auth print-access-token 指令擷取存取權杖,驗證與各種 Google Cloud API 的互動
    • PROJECT_IDREGIONKUBERNETES_CLUSTER_PREFIX 是在「設定環境」一節中定義的環境變數,並指派給您要建立的 Autopilot 叢集的新相關變數。

    系統顯示提示訊息時,請輸入 yes

    輸出結果會與下列內容相似:

    ...
    Apply complete! Resources: 9 added, 0 changed, 0 destroyed.
    
    Outputs:
    
    kubectl_connection_command = "gcloud container clusters get-credentials elasticsearch-cluster --region us-central1"
    

    Terraform 會建立下列資源:

    • Kubernetes 節點的自訂虛擬私有雲網路和私人子網路。
    • 透過網路位址轉譯 (NAT) 存取網際網路的 Cloud Router。
    • us-central1 地區的私人 GKE 叢集。
    • 具有叢集記錄和監控權限的 ServiceAccount
    • Google Cloud Managed Service for Prometheus 設定,用於叢集監控和快訊。

    標準

    下圖顯示部署在三個不同區域的標準私人區域 GKE 叢集。

    GKE Standard 叢集

    如要部署叢集基礎架構,請在 Cloud Shell 中執行下列指令:

    export GOOGLE_OAUTH_ACCESS_TOKEN=$(gcloud auth print-access-token)
    terraform -chdir=terraform/gke-standard init
    terraform -chdir=terraform/gke-standard apply \
    -var project_id=${PROJECT_ID} \
    -var region=${REGION} \
    -var cluster_prefix=${KUBERNETES_CLUSTER_PREFIX}
    

    GKE 會在執行階段替換下列變數:

    • GOOGLE_OAUTH_ACCESS_TOKEN 會使用 gcloud auth print-access-token 指令擷取存取權杖,驗證與各種 Google Cloud API 的互動。
    • PROJECT_IDREGIONKUBERNETES_CLUSTER_PREFIX 是在「設定環境」一節中定義的環境變數,並指派給您要建立的 Standard 叢集的新相關變數。

    系統顯示提示訊息時,請輸入 yes。這些指令可能需要幾分鐘才能完成,叢集也會在幾分鐘後顯示就緒狀態。

    輸出結果會與下列內容相似:

    ...
    Apply complete! Resources: 10 added, 0 changed, 0 destroyed.
    
    Outputs:
    
    kubectl_connection_command = "gcloud container clusters get-credentials elasticsearch-cluster --region us-central1"
    

    Terraform 會建立下列資源:

    • Kubernetes 節點的自訂虛擬私有雲網路和私人子網路。
    • 透過網路位址轉譯 (NAT) 存取網際網路的 Cloud Router。
    • us-central1 地區中已啟用自動調度的私人 GKE 叢集 (每個區域有一到兩個節點)。
    • 具有叢集記錄和監控權限的 ServiceAccount
    • Google Cloud Managed Service for Prometheus 設定,用於叢集監控和快訊。

    連線至叢集

    設定 kubectl,以擷取憑證並與新的 GKE 叢集通訊:

    gcloud container clusters get-credentials \
        ${KUBERNETES_CLUSTER_PREFIX}-cluster --location ${REGION}
    

    部署 Elasticsearch 資料庫和 StatefulHA 運算子

    在本節中,您將使用 ECK Operator Helm 圖表,將 Elasticsearch 資料庫 (叢集模式) 和 StatefulHA 運算子部署至 GKE 叢集。

    這個 Deployment 會建立 GKE 叢集,並採用下列設定:

    • 三個 Elasticsearch 節點副本。
    • DaemonSet,以變更虛擬記憶體設定,達到最佳 Elasticsearch 效能。DaemonSet 是 Kubernetes 控制器,可確保 Pod 副本在叢集中的每個節點上執行。
    • 設定 NodeAffinity 和 PodAntiAffinity,確保在 Kubernetes 節點間適當分配,進而最佳化節點集區的使用情形,並盡可能提高不同區域的可用性。
    • 管理容錯移轉程序並確保高可用性的 Stateful HA 運算子。StatefulSet 是 Kubernetes 控制器,可為每個 Pod 維護永久專屬 ID。
    • 為進行驗證,資料庫會使用驗證憑證、密碼和憑證建立 Kubernetes 密鑰。

    如要使用 Helm 圖表部署 Elasticsearch 資料庫,請按照下列步驟操作:

    1. 啟用 StatefulHA 外掛程式

      Autopilot

      GKE 會在建立叢集時自動啟用 StatefulHA 外掛程式。

      標準

      執行下列指令:

      gcloud container clusters update ${KUBERNETES_CLUSTER_PREFIX}-cluster \
          --project=${PROJECT_ID} \
          --location=${REGION} \
          --update-addons=StatefulHA=ENABLED
      

      這項指令可能需要 15 分鐘才能完成,且叢集會顯示就緒狀態。

    2. 建立 Kubernetes 上的 Elastic Cloud (ECK) 自訂資源定義 (CRD):

      kubectl apply -f https://download.elastic.co/downloads/eck/2.11.1/crds.yaml
      
    3. 部署 ECK 運算子:

      kubectl apply -f https://download.elastic.co/downloads/eck/2.11.1/operator.yaml
      
    4. 為資料庫建立 elastic 命名空間:

      kubectl create ns elastic
      
    5. 安裝 HighAvailabilityApplication (HAA) 資源,定義 Elasticsearch 的容錯移轉規則。

      kubectl apply -n elastic -f manifests/01-regional-pd/ha-app.yaml
      

      ha-app.yaml 資訊清單說明 HighAvailabilityApplication 資源:

      kind: HighAvailabilityApplication
      apiVersion: ha.gke.io/v1
      metadata:
        name: elasticsearch-ha-es-main
        namespace: elastic
      spec:
        resourceSelection:
          resourceKind: StatefulSet
        policy:
          storageSettings:
            requireRegionalStorage: false
          failoverSettings:
            forceDeleteStrategy: AfterNodeUnreachable
            afterNodeUnreachable:
              afterNodeUnreachableSeconds: 20 # 60 seconds total
    6. 套用資訊清單,建立地區永久 SSD 磁碟 StorageClass

      kubectl apply -n elastic -f manifests/01-regional-pd/regional-pd.yaml
      

      regional-pd.yaml資訊清單會說明永久 SSD 磁碟 StorageClass

      apiVersion: storage.k8s.io/v1
      kind: StorageClass
      allowVolumeExpansion: true
      metadata:
        name: ha-regional
      parameters:
        replication-type: regional-pd
        type: pd-ssd
        availability-class: regional-hard-failover
      provisioner: pd.csi.storage.gke.io
      reclaimPolicy: Retain
      volumeBindingMode: WaitForFirstConsumer
    7. 部署 DaemonSet 資源,在每個節點中設定虛擬記憶體:

      kubectl apply -n elastic -f manifests/02-elasticsearch/mmap-count.yaml
      

      mmap-count.yaml 資訊清單會說明 DaemonSet

      apiVersion: apps/v1
      kind: DaemonSet
      metadata:
        name: max-map-count-setter
        labels:
          k8s-app: max-map-count-setter
      spec:
        selector:
          matchLabels:
            name: max-map-count-setter
        template:
          metadata:
            labels:
              name: max-map-count-setter
          spec:
            initContainers:
              - name: max-map-count-setter
                image: docker.io/bash:5.2.21
                resources:
                  limits:
                    cpu: 100m
                    memory: 32Mi
                securityContext:
                  privileged: true
                  runAsUser: 0
                command: ['/usr/local/bin/bash', '-e', '-c', 'echo 262144 > /proc/sys/vm/max_map_count']
            containers:
              - name: sleep
                image: docker.io/bash:5.2.21
                command: ['sleep', 'infinity']
    8. 套用資訊清單來部署 Elasticsearch 叢集:

      kubectl apply -n elastic -f manifests/02-elasticsearch/elasticsearch.yaml
      

      elasticsearch.yaml 資訊清單會說明 Deployment:

      apiVersion: elasticsearch.k8s.elastic.co/v1
      kind: Elasticsearch
      metadata:
        name: elasticsearch-ha
      spec:
        version: 8.11.4
        nodeSets:
        - name: main
          count: 3
          volumeClaimTemplates:
          - metadata:
              name: elasticsearch-data 
            spec:
              accessModes:
              - ReadWriteOnce
              resources:
                requests:
                  storage: 10Gi
              storageClassName: ha-regional
          config:
          podTemplate:
            metadata:
              labels:
                app.stateful/component: elasticsearch
            spec:
              initContainers:
              - name: max-map-count-check
                command: ['sh', '-c', "while true; do mmc=$(cat /proc/sys/vm/max_map_count); if [ ${mmc} -eq 262144 ]; then exit 0; fi; sleep 1; done"]
              containers:
              - name: metrics
                image: quay.io/prometheuscommunity/elasticsearch-exporter:v1.7.0
                command:
                  - /bin/elasticsearch_exporter
                  - --es.ssl-skip-verify
                  - --es.uri=https://$(ES_USER):$(ES_PASSWORD)@localhost:9200
                securityContext:
                  runAsNonRoot: true
                  runAsGroup: 10000
                  runAsUser: 10000
                resources:
                  requests:
                    memory: "128Mi"
                    cpu: "25m"
                  limits:
                    memory: "128Mi"
                    cpu: "100m"
                ports:
                - containerPort: 9114
                env:
                - name: ES_USER
                  value: "elastic"
                - name: ES_PASSWORD
                  valueFrom:
                    secretKeyRef:
                      name: elasticsearch-ha-es-elastic-user
                      key: elastic
              - name: elasticsearch
                resources:
                  limits:
                    memory: 4Gi
                    cpu: 1
              affinity:
                nodeAffinity:
                  preferredDuringSchedulingIgnoredDuringExecution:
                    - weight: 1
                      preference:
                        matchExpressions:
                        - key: app.stateful/component
                          operator: In
                          values:
                          - elasticsearch
                podAntiAffinity:
                  preferredDuringSchedulingIgnoredDuringExecution:
                  - weight: 1
                    podAffinityTerm:
                      labelSelector:
                        matchLabels:
                          app.stateful/component: elasticsearch
                      topologyKey: topology.kubernetes.io/zone

      等待幾分鐘,讓 Elasticsearch 叢集完全啟動。

    9. 檢查部署狀態:

      kubectl get elasticsearch -n elastic --watch
      

      如果成功部署 elasticsearch 資料庫,輸出內容會類似如下:

      NAME               HEALTH   NODES   VERSION   PHASE   AGE
      elasticsearch-ha   green    3       8.11.4    Ready   2m30s
      

      等待 HEALTH 顯示為 green。如有需要,請按下 Ctrl+C 鍵結束指令。

    10. 部署內部負載平衡器,存取與 GKE 叢集位於相同 VPC 的 Elasticsearch 資料庫:

      kubectl apply -n elastic -f manifests/02-elasticsearch/ilb.yaml
      

      ilb.yaml 資訊清單說明 LoadBalancer 服務:

      apiVersion: v1
      kind: Service
      metadata:
        annotations:
          #cloud.google.com/neg: '{"ingress": true}'
          networking.gke.io/load-balancer-type: "Internal"
        labels:
          app.kubernetes.io/name: elasticsearch
        name: elastic-ilb
      spec:
        ports:
        - name: https
          port: 9200
          protocol: TCP
          targetPort: 9200
        selector:
          common.k8s.elastic.co/type: elasticsearch
          elasticsearch.k8s.elastic.co/cluster-name: elasticsearch-ha
        type: LoadBalancer
    11. 如要確認是否已套用容錯移轉規則,請說明資源並確認 Status: Message: Application is protected

      kubectl describe highavailabilityapplication elasticsearch-ha-es-main -n elastic
      

      輸出內容類似如下

      Status:
        Conditions:
          Last Transition Time:  2024-02-01T13:27:50Z
          Message:               Application is protected
          Observed Generation:   1
          Reason:                ApplicationProtected
          Status:                True
          Type:                  Protected
      Events:                    <none>
      
    12. GKE 啟動工作負載後,請確認 GKE 已建立 Elasticsearch 工作負載:

      kubectl get pod,svc,statefulset,pdb,secret,daemonset -n elastic
      

      輸出結果會與下列內容相似:

      NAME                             READY   STATUS    RESTARTS   AGE
      pod/elasticsearch-ha-es-main-0   2/2     Running   0          7m16s
      pod/elasticsearch-ha-es-main-1   2/2     Running   0          7m16s
      pod/elasticsearch-ha-es-main-2   2/2     Running   0          7m16s
      pod/max-map-count-setter-28wt9   1/1     Running   0          7m27s
      pod/max-map-count-setter-cflsw   1/1     Running   0          7m27s
      pod/max-map-count-setter-gzq9k   1/1     Running   0          7m27s
      
      NAME                                        TYPE        CLUSTER-IP    EXTERNAL-IP   PORT(S)    AGE
      service/elasticsearch-ha-es-http            ClusterIP   10.52.8.28   <none>        9200/TCP   7m18s
      service/elasticsearch-ha-es-internal-http   ClusterIP   10.52.3.48   <none>        9200/TCP   7m18s
      service/elasticsearch-ha-es-main            ClusterIP   None         <none>        9200/TCP   7m16s
      service/elasticsearch-ha-es-transport       ClusterIP   None         <none>        9300/TCP   7m18s
      
      NAME                                        READY   AGE
      statefulset.apps/elasticsearch-ha-es-main   3/3     7m16s
      
      NAME                                                     MIN AVAILABLE   MAX UNAVAILABLE   ALLOWED DISRUPTIONS   AGE
      poddisruptionbudget.policy/elasticsearch-ha-es-default   2               N/A               1                     7m16s
      
      NAME                                                 TYPE     DATA   AGE
      secret/elasticsearch-ha-es-elastic-user              Opaque   1      7m18s
      secret/elasticsearch-ha-es-file-settings             Opaque   1      7m16s
      secret/elasticsearch-ha-es-http-ca-internal          Opaque   2      7m17s
      secret/elasticsearch-ha-es-http-certs-internal       Opaque   3      7m17s
      secret/elasticsearch-ha-es-http-certs-public         Opaque   2      7m17s
      secret/elasticsearch-ha-es-internal-users            Opaque   4      7m18s
      secret/elasticsearch-ha-es-main-es-config            Opaque   1      7m16s
      secret/elasticsearch-ha-es-main-es-transport-certs   Opaque   7      7m16s
      secret/elasticsearch-ha-es-remote-ca                 Opaque   1      7m16s
      secret/elasticsearch-ha-es-transport-ca-internal     Opaque   2      7m16s
      secret/elasticsearch-ha-es-transport-certs-public    Opaque   1      7m16s
      secret/elasticsearch-ha-es-xpack-file-realm          Opaque   4      7m18s
      
      NAME                                  DESIRED   CURRENT   READY   UP-TO-DATE   AVAILABLE   NODE SELECTOR   AGE
      daemonset.apps/max-map-count-setter   6         6         6       6            6           <none>          13m
      

    系統會為 Elasticsearch 叢集建立下列 GKE 資源:

    • 控制三個 Pod 副本的 Elasticsearch StatefulSet
    • 用於設定虛擬記憶體設定的 DaemonSet。
    • 連線至 Elasticsearch 的服務。
    • 含有超級使用者憑證和服務相關憑證的密鑰。
    • 有狀態的 HA 運算子 Pod 和 HighlyAvailableApplication 資源,主動監控 Elasticsearch 應用程式。

    使用 Vertex AI Colab Enterprise 筆記本執行查詢

    本節說明如何使用 Colab Enterprise 筆記本中的官方 Elasticsearch Python 用戶端,將嵌入內容產生至 Elasticsearch 文件,並執行語意搜尋查詢。Elasticsearch 中的文件由各種欄位組成,每個欄位都與對應的值配對。

    如要進一步瞭解 Vertex AI Colab Enterprise,請參閱 Colab Enterprise 說明文件

    最佳做法

    為有效運用 Elasticsearch,建議您將資料架構到這些文件中,然後編製索引以供搜尋。

    在本範例中,您會使用 CSV 檔案中的資料集,其中包含不同類型書籍的清單。Elasticsearch 可做為搜尋引擎,您建立的 Pod 則可做為查詢 Elasticsearch 資料庫的用戶端。

    您可以使用專屬的執行階段範本部署至 elasticsearch-vpc VPC (虛擬私有雲),因此筆記本可以與 GKE 叢集中的資源通訊。

    建立執行階段範本

    如要建立 Colab Enterprise 執行階段範本,請按照下列步驟操作:

    1. 在 Google Cloud 控制台中,前往 Colab Enterprise 的「Runtime Templates」(執行階段範本) 頁面,並確認已選取專案:

      前往「執行階段範本」

    2. 按一下「新增範本」。「建立新的執行階段範本」頁面隨即顯示。

    3. 在「執行階段基本資訊」部分:

      • 在「Display name」(顯示名稱) 欄位中,輸入 elastic-connect
      • 在「Region」(區域) 下拉式清單中選取「us-central1」。與 GKE 叢集位於相同地區。
    4. 在「設定運算」部分:

      • 在「Machine type」(機器類型) 下拉式清單中,選取「e2-standard-2」。
      • 在「Disk size」(磁碟大小) 欄位中,輸入 30
    5. 在「網路與安全性」部分中:

      • 在「Network」(網路) 下拉式選單中,選取 GKE 叢集所在的網路。
      • 在「Subnetwork」(子網路) 下拉式清單中,選取對應的子網路。
      • 取消勾選「啟用公開網際網路存取權」核取方塊。
    6. 按一下「建立」,完成建立執行階段範本。執行階段範本會顯示在「執行階段範本」分頁的清單中。

    建立執行階段

    如要建立 Colab Enterprise 執行階段,請按照下列步驟操作:

    1. 在剛建立的範本執行階段範本清單中,按一下「動作」欄中的 ,然後點選「建立執行階段」。系統隨即會顯示「Create Vertex AI Runtime」(建立 Vertex AI 執行階段) 窗格。

    2. 如要根據範本建立執行階段,請按一下「建立」

    3. 在開啟的「執行階段」分頁中,等待狀態轉換為「正常」

    匯入筆記本

    如要在 Colab Enterprise 中匯入筆記本,請按照下列步驟操作:

    1. 前往「我的筆記本」分頁,然後按一下「匯入」。「匯入筆記本」窗格隨即顯示。

    2. 在「匯入來源」中,選取「網址」

    3. 在「筆記本網址」下方,輸入下列連結:

      https://raw.githubusercontent.com/GoogleCloudPlatform/kubernetes-engine-samples/main/databases/elasticsearch/manifests/03-notebook/vector-database.ipynb
      
    4. 按一下「匯入」

    連線至執行階段並執行查詢

    如要連線至執行階段並執行查詢,請按照下列步驟操作:

    1. 在筆記本中,按一下「連線」按鈕旁邊的 「其他連線選項」。 系統隨即會顯示「Connect to Vertex AI Runtime」(連線至 Vertex AI 執行階段) 窗格。

    2. 選取「連線到執行階段」,然後選取「連線至現有的執行階段」

    3. 選取啟動的執行階段,然後按一下「連線」

    4. 如要執行筆記本儲存格,請按一下每個程式碼儲存格旁邊的 「Run cell」(執行儲存格) 按鈕。

    筆記本包含程式碼儲存格和說明每個程式碼區塊的文字。執行程式碼儲存格會執行其指令並顯示輸出內容。您可以依序執行儲存格,也可以視需要執行個別儲存格。

    查看叢集的 Prometheus 指標

    GKE 叢集已設定 Google Cloud Managed Service for Prometheus,可收集 Prometheus 格式的指標。這項服務提供全代管的監控和快訊解決方案,可收集、儲存及分析叢集和應用程式的指標。

    下圖顯示 Prometheus 如何收集叢集的指標:

    收集 Prometheus 指標

    圖中的 GKE 私人叢集包含下列元件:

    • 在路徑 / 和通訊埠 9114 上公開指標的 Elasticsearch Pod。這些指標是由名為 metrics 的補充資訊容器提供,該容器包含 elasticsearch_exporter
    • 以 Prometheus 為基礎的收集器,可處理來自 Elasticsearch Pod 的指標。
    • 將指標傳送至 Cloud Monitoring 的 PodMonitoring 資源。

    叢集設定會定義具有指標匯出工具的補充容器,格式為 Prometheus:

    apiVersion: elasticsearch.k8s.elastic.co/v1
    kind: Elasticsearch
    metadata:
      name: elasticsearch-ha
    spec:
      ...
      nodeSets:
      - name: main
        ...
        podTemplate:
          spec:
            containers:
            ...
            - name: metrics
              image: quay.io/prometheuscommunity/elasticsearch-exporter:v1.7.0
              command:
              - /bin/elasticsearch_exporter
              - --es.ssl-skip-verify
              - --es.uri=https://$(ES_USER):$(ES_PASSWORD)@localhost:9200
              ...
              env:
              - name: ES_USER
                value: "elastic"
              - name: ES_PASSWORD
                valueFrom:
                secretKeyRef:
                  name: elasticsearch-ha-es-elastic-user
                  key: elastic
    

    如要匯出及查看指標,請按照下列步驟操作:

    1. 建立 PodMonitoring 資源,以透過 labelSelector 抓取指標:

      kubectl apply -n elastic -f manifests/04-prometheus-metrics/pod-monitoring.yaml
      

      pod-monitoring.yaml 資訊清單說明 PodMonitoring 資源:

      apiVersion: monitoring.googleapis.com/v1
      kind: PodMonitoring
      metadata:
        name: elasticsearch
      spec:
        selector:
          matchLabels:
            app.stateful/component: elasticsearch
            elasticsearch.k8s.elastic.co/cluster-name: elasticsearch-ha
        endpoints:
        - port: 9114
          interval: 30s
          path: /metrics

      幾分鐘後,系統會顯示內建資訊主頁「Elasticsearch Prometheus Overview」。

    2. 如要查看更多資料相關圖表,請匯入自訂 Cloud Monitoring 資訊主頁,並使用 dashboard.json 中定義的設定:

      gcloud --project "${PROJECT_ID}" monitoring dashboards create --config-from-file monitoring/dashboard.json
      
    3. 指令順利執行後,請前往 Cloud Monitoring 的「資訊主頁」

      前往資訊主頁總覽

    4. 從資訊主頁清單中開啟 ElasticSearch Overview 資訊主頁。系統可能需要 1 到 2 分鐘才能收集及顯示指標。

      資訊主頁會顯示主要指標的計數:

      • 索引
      • 文件和分片
      • 待處理的作業
      • 執行節點並顯示健康狀態

    備份叢集設定

    GKE 備份功能可讓您排定定期備份整個 GKE 叢集設定,包括已部署的工作負載及其資料。

    在本教學課程中,您將為 GKE 叢集設定備份計畫,每天凌晨 3 點備份所有工作負載,包括 Secret 和 Volume。為確保儲存空間管理效率,系統會自動刪除超過三天的備份。

    1. 為叢集啟用 GKE 備份功能:

      gcloud container clusters update ${KUBERNETES_CLUSTER_PREFIX}-cluster \
          --project=${PROJECT_ID} \
          --location=${REGION} \
          --update-addons=BackupRestore=ENABLED
      
    2. 為叢集內的所有命名空間建立每日排程的備份方案:

      gcloud beta container backup-restore backup-plans create ${KUBERNETES_CLUSTER_PREFIX}-cluster-backup \
          --project=${PROJECT_ID} \
          --location=${REGION} \
          --cluster="projects/${PROJECT_ID}/locations/${REGION}/clusters/${KUBERNETES_CLUSTER_PREFIX}-cluster" \
          --all-namespaces \
          --include-secrets \
          --include-volume-data \
          --cron-schedule="0 3 * * *" \
          --backup-retain-days=3
      

      這個指令會在執行階段使用相關環境變數。

      叢集名稱的格式與專案和區域相關,如下所示:

      projects/PROJECT_ID/locations/REGION/clusters/CLUSTER_NAME
      

      出現提示時,請輸入 y.輸出內容會與下列內容相似:

      Create request issued for: [elasticsearch-cluster-backup]
      Waiting for operation [projects/PROJECT_ID/locations/us-central1/operations/operation-1706528750815-610142ffdc9ac-71be4a05-f61c99fc] to complete...⠹
      

      這項作業可能需要幾分鐘才能順利完成。執行完成後,輸出內容會類似如下:

      Created backup plan [elasticsearch-cluster-backup].
      
    3. 您可以在 GKE 備份控制台看到新建立的備份方案 elasticsearch-cluster-backup

      前往 GKE 備份

    如要還原已儲存的備份設定,請參閱「還原備份」。

    清除所用資源

    如要避免系統向您的 Google Cloud 帳戶收取本教學課程中所用資源的相關費用,請刪除含有該項資源的專案,或者保留專案但刪除個別資源。

    刪除專案

    如要避免付費,最簡單的方法就是刪除您為本教學課程建立的專案。

    Delete a Google Cloud project:

    gcloud projects delete PROJECT_ID

    如果您已刪除專案,則清理作業完成。如果沒有刪除專案,請繼續刪除個別資源。

    刪除個別資源

    1. 設定環境變數。

      export PROJECT_ID=${PROJECT_ID}
      export KUBERNETES_CLUSTER_PREFIX=elasticsearch
      export REGION=us-central1
      
    2. 執行 terraform destroy 指令:

      export GOOGLE_OAUTH_ACCESS_TOKEN=$(gcloud auth print-access-token)
      terraform  -chdir=terraform/FOLDER destroy \
      -var project_id=${PROJECT_ID} \
      -var region=${REGION} \
      -var cluster_prefix=${KUBERNETES_CLUSTER_PREFIX}
      

      根據您建立的 GKE 叢集類型,將 FOLDER 替換為 gke-autopilotgke-standard

      系統顯示提示訊息時,請輸入 yes

    3. 找出所有未連接的磁碟:

      export disk_list=$(gcloud compute disks list --filter="-users:* AND labels.name=${KUBERNETES_CLUSTER_PREFIX}-cluster" --format "value[separator=|](name,region)")
      
    4. 刪除磁碟:

      for i in $disk_list; do
       disk_name=$(echo $i| cut -d'|' -f1)
       disk_region=$(echo $i| cut -d'|' -f2|sed 's|.*/||')
       echo "Deleting $disk_name"
       gcloud compute disks delete $disk_name --region $disk_region --quiet
      done
      
    5. 刪除 GitHub 存放區:

      rm -r ~/kubernetes-engine-samples/
      

    後續步驟