在 GKE 上大規模執行全端工作負載


本教學課程說明如何在 Google Kubernetes Engine (GKE) 中,大規模執行以高可用性關聯式資料庫為後端的網頁應用程式。

本教學課程使用的範例應用程式是 Bank of Anthos,這是一個以 HTTP 為基礎的網路應用程式,可模擬銀行的付款處理網路。Bank of Anthos 需使用多項服務才能運作。本教學課程著重於網站前端,以及支援 Bank of Anthos 服務的關聯式 PostgreSQL 資料庫。如要進一步瞭解 Bank of Anthos,包括其架構和部署的服務,請參閱 GitHub 上的 Bank of Anthos

目標

  • 建立及設定 GKE 叢集。
  • 部署範例網頁應用程式和高可用性 PostgreSQL 資料庫。
  • 設定網頁應用程式和資料庫的自動調度資源功能。
  • 使用負載產生器模擬流量尖峰。
  • 觀察服務的擴充和縮減情形。

費用

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

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

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

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

事前準備

  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. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  4. To initialize the gcloud CLI, run the following command:

    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. Make sure that billing is enabled for your Google Cloud project.

  7. Enable the GKE API:

    gcloud services enable container.googleapis.com
  8. Install the Google Cloud CLI.

  9. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  10. To initialize the gcloud CLI, run the following command:

    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. Make sure that billing is enabled for your Google Cloud project.

  13. Enable the GKE API:

    gcloud services enable container.googleapis.com
  14. 安裝 Helm CLI

準備環境

  1. 複製本教學課程中使用的範例存放區:

    git clone https://github.com/GoogleCloudPlatform/bank-of-anthos.git
    cd bank-of-anthos/
    
  2. 設定環境變數:

    PROJECT_ID=PROJECT_ID
    GSA_NAME=bank-of-anthos
    GSA_EMAIL=bank-of-anthos@${PROJECT_ID}.iam.gserviceaccount.com
    KSA_NAME=default
    

    並將 PROJECT_ID 改成您的專案 ID。 Google Cloud

設定叢集和服務帳戶

  1. 建立叢集:

    gcloud container clusters create-auto bank-of-anthos --region=us-central1
    

    叢集最多可能需要五分鐘才會啟動。

  2. 建立 IAM 服務帳戶:

    gcloud iam service-accounts create bank-of-anthos
    
  3. 授予 IAM 服務帳戶存取權:

    gcloud projects add-iam-policy-binding PROJECT_ID \
      --role roles/cloudtrace.agent \
      --member "serviceAccount:bank-of-anthos@PROJECT_ID.iam.gserviceaccount.com"
    gcloud projects add-iam-policy-binding PROJECT_ID \
      --role roles/monitoring.metricWriter \
      --member "serviceAccount:bank-of-anthos@PROJECT_ID.iam.gserviceaccount.com"
    gcloud iam service-accounts add-iam-policy-binding "bank-of-anthos@PROJECT_ID.iam.gserviceaccount.com" \
      --role roles/iam.workloadIdentityUser \
      --member "serviceAccount:PROJECT_ID.svc.id.goog[default/default]"
    

    這個步驟會授予下列存取權:

    • roles/cloudtrace.agent:將延遲資訊等追蹤資料寫入 Trace。
    • roles/monitoring.metricWriter:將指標寫入 Cloud Monitoring。
    • roles/iam.workloadIdentityUser:允許 Kubernetes 服務帳戶使用 Workload Identity Federation for GKE,以 IAM 服務帳戶的身分運作。
  4. default 命名空間中設定 default Kubernetes 服務帳戶,做為您建立的 IAM 服務帳戶:

    kubectl annotate serviceaccount default \
        iam.gke.io/gcp-service-account=bank-of-anthos@PROJECT_ID.iam.gserviceaccount.com
    

    這樣一來,使用 default 命名空間中 default Kubernetes 服務帳戶的 Pod,就能存取與 IAM 服務帳戶相同的 Google Cloud 資源。

部署 Bank of Anthos 和 PostgreSQL

在本節中,您將以高可用性 (HA) 模式安裝 Bank of Anthos 和 PostgreSQL 資料庫,以便自動調整資料庫伺服器副本的規模。如要查看本節使用的指令碼、Helm 資訊圖表和 Kubernetes 資訊清單,請前往 GitHub 上的 Bank of Anthos 存放區

  1. 部署資料庫結構定義和資料定義語言 (DDL) 指令碼:

    kubectl create configmap initdb \
        --from-file=src/accounts/accounts-db/initdb/0-accounts-schema.sql \
        --from-file=src/accounts/accounts-db/initdb/1-load-testdata.sql \
        --from-file=src/ledger/ledger-db/initdb/0_init_tables.sql \
        --from-file=src/ledger/ledger-db/initdb/1_create_transactions.sh
    
  2. 使用範例 Helm Chart 安裝 PostgreSQL:

    helm repo add bitnami https://charts.bitnami.com/bitnami
    helm install accounts-db bitnami/postgresql-ha \
        --version 10.0.1 \
        --values extras/postgres-hpa/helm-postgres-ha/values.yaml \
        --set="postgresql.initdbScriptsCM=initdb" \
        --set="postgresql.replicaCount=1" \
        --wait
    

    這項指令會建立 PostgreSQL 叢集,起始副本數為 1。 在本教學課程的後續部分,您將根據連線數調度叢集資源。這項作業可能需要十分鐘以上的時間才能完成。

  3. 部署 Bank of Anthos:

    kubectl apply -f extras/jwt/jwt-secret.yaml
    kubectl apply -f extras/postgres-hpa/kubernetes-manifests
    

    這項作業可能需要幾分鐘才能完成。

檢查點:驗證設定

  1. 確認所有 Bank of Anthos Pod 都在執行中:

    kubectl get pods
    

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

    NAME                                  READY   STATUS
    accounts-db-pgpool-57ffc9d685-c7xs8   3/3     Running
    accounts-db-postgresql-0              1/1     Running
    balancereader-57b59769f8-xvp5k        1/1     Running
    contacts-54f59bb669-mgsqc             1/1     Running
    frontend-6f7fdc5b65-h48rs             1/1     Running
    ledgerwriter-cd74db4cd-jdqql          1/1     Running
    pgpool-operator-5f678457cd-cwbhs      1/1     Running
    transactionhistory-5b9b56b5c6-sz9qz   1/1     Running
    userservice-f45b46b49-fj7vm           1/1     Running
    
  2. 確認你可以存取網站前端:

    1. 取得 frontend 服務的外部 IP 位址:

      kubectl get ingress frontend
      

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

      NAME       CLASS    HOSTS   ADDRESS         PORTS   AGE
      frontend   <none>   *       203.0.113.9     80      12m
      
    2. 在瀏覽器中前往外部 IP 位址。系統會顯示 Bank of Anthos 登入頁面。如有興趣,請探索應用程式。

      如果收到 404 錯誤,請稍候幾分鐘,讓微服務完成佈建,然後再試一次。

自動調整網頁應用程式和 PostgreSQL 資料庫的規模

GKE Autopilot 會根據叢集中的工作負載數量,自動調整叢集運算資源。如要根據資源指標自動調整叢集中的 Pod 數量,請實作 Kubernetes 水平自動調度 Pod 資源。您可以使用內建的 Kubernetes CPU 和記憶體指標,也可以使用自訂指標,例如每秒 HTTP 要求數或 SELECT 陳述式數量 (取自 Cloud Monitoring)。

在本節中,執行以下操作:

  1. 使用內建指標和自訂指標,為 Bank of Anthos 微服務設定水平 Pod 自動調度資源。
  2. 模擬 Bank of Anthos 應用程式的負載,觸發自動調度資源事件。
  3. 觀察叢集中的 Pod 和節點數量如何因應負載,自動向上和向下調度資源。

設定自訂指標收集

如要從 Monitoring 讀取自訂指標,您必須在叢集中部署自訂指標 - Stackdriver 轉接器

  1. 部署轉接程式:

    kubectl apply -f https://raw.githubusercontent.com/GoogleCloudPlatform/k8s-stackdriver/master/custom-metrics-stackdriver-adapter/deploy/production/adapter.yaml
    
  2. 設定介面卡,使用 Workload Identity Federation for GKE 取得指標:

    1. 設定 IAM 服務帳戶:

      gcloud projects add-iam-policy-binding PROJECT_ID \
          --member "serviceAccount:bank-of-anthos@PROJECT_ID.iam.gserviceaccount.com" \
          --role roles/monitoring.viewer
      gcloud iam service-accounts add-iam-policy-binding bank-of-anthos@PROJECT_ID.iam.gserviceaccount.com \
          --role roles/iam.workloadIdentityUser \
          --member "serviceAccount:PROJECT_ID.svc.id.goog[custom-metrics/custom-metrics-stackdriver-adapter]"
      
    2. 為介面卡使用的 Kubernetes 服務帳戶加上註解:

      kubectl annotate serviceaccount custom-metrics-stackdriver-adapter \
          --namespace=custom-metrics \
        iam.gke.io/gcp-service-account=bank-of-anthos@PROJECT_ID.iam.gserviceaccount.com
      
    3. 重新啟動轉接器部署作業,以傳播變更:

      kubectl rollout restart deployment custom-metrics-stackdriver-adapter \
          --namespace=custom-metrics
      

設定資料庫的自動調度資源功能

在本教學課程稍早部署 Bank of Anthos 和 PostgreSQL 時,您已將資料庫部署為 StatefulSet,並使用一個主要讀取/寫入副本來處理所有傳入的 SQL 陳述式。在本節中,您會設定水平 Pod 自動調度資源功能,新增備用唯讀副本來處理傳入的 SELECT 陳述式。如要減少每個副本的負載,最好的方法就是分配 SELECT 陳述式 (讀取作業)。PostgreSQL 部署作業包含名為 Pgpool-II 的工具,可達成這項負載平衡,並提升系統的處理量。

PostgreSQL 會將 SELECT 陳述式指標匯出為 Prometheus 指標。您將使用名為 prometheus-to-sd 的輕量型指標匯出工具,以支援的格式將這些指標傳送至 Cloud Monitoring。

  1. 查看 HorizontalPodAutoscaler 物件:

    # Copyright 2022 Google LLC
    #
    # Licensed under the Apache License, Version 2.0 (the "License");
    # you may not use this file except in compliance with the License.
    # You may obtain a copy of the License at
    #
    #      http://www.apache.org/licenses/LICENSE-2.0
    #
    # Unless required by applicable law or agreed to in writing, software
    # distributed under the License is distributed on an "AS IS" BASIS,
    # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    # See the License for the specific language governing permissions and
    # limitations under the License.
    
    ---
    apiVersion: autoscaling/v2
    kind: HorizontalPodAutoscaler
    metadata:
      name: accounts-db-postgresql
    spec:
      behavior:
        scaleUp:
          stabilizationWindowSeconds: 0
          policies:
          - type: Percent
            value: 100
            periodSeconds: 5
          selectPolicy: Max
      scaleTargetRef:
        apiVersion: apps/v1
        kind: StatefulSet
        name: accounts-db-postgresql
      minReplicas: 1
      maxReplicas: 5
      metrics:
      - type: External
        external:
          metric:
            name: custom.googleapis.com|mypgpool|pgpool2_pool_backend_stats_select_cnt
          target:
              type: AverageValue
              averageValue: "15"
    

    這個資訊清單會執行下列操作:

    • 將擴充期間的備用資源數量上限設為 5
    • 將縮減期間的執行個體數量下限設為 1
    • 使用外部指標做出資源調度決策。在本範例中,指標是 SELECT 陳述式的數量。如果傳入的 SELECT 陳述式數量超過 15 個,就會發生擴充事件。
  2. 將資訊清單套用至叢集:

    kubectl apply -f extras/postgres-hpa/hpa/postgresql-hpa.yaml
    

設定網頁介面的自動調度資源功能

在「部署 Bank of Anthos 和 PostgreSQL」中,您部署了 Bank of Anthos 網頁介面。使用者人數增加時,userservice服務會消耗更多 CPU 資源。在本節中,您將為 userservice Deployment 設定水平 Pod 自動調度功能,當現有 Pod 的 CPU 使用量超過要求量的 60% 時,以及為 frontend Deployment 設定水平 Pod 自動調度功能,當負載平衡器的 HTTP 要求數超過每秒 5 個時,就會自動調度資源。

為 userservice Deployment 設定自動調度資源功能

  1. 查看 Deployment 的 HorizontalPodAutoscaler資訊清單:userservice

    # Copyright 2022 Google LLC
    #
    # Licensed under the Apache License, Version 2.0 (the "License");
    # you may not use this file except in compliance with the License.
    # You may obtain a copy of the License at
    #
    #      http://www.apache.org/licenses/LICENSE-2.0
    #
    # Unless required by applicable law or agreed to in writing, software
    # distributed under the License is distributed on an "AS IS" BASIS,
    # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    # See the License for the specific language governing permissions and
    # limitations under the License.
    
    ---
    apiVersion: autoscaling/v2
    kind: HorizontalPodAutoscaler
    metadata:
      name: userservice
    spec:
      behavior:
        scaleUp:
          stabilizationWindowSeconds: 0
          policies:
            - type: Percent
              value: 100
              periodSeconds: 5
          selectPolicy: Max
      scaleTargetRef:
        apiVersion: apps/v1
        kind: Deployment
        name: userservice
      minReplicas: 5
      maxReplicas: 50
      metrics:
        - type: Resource
          resource:
            name: cpu
            target:
              type: Utilization
              averageUtilization: 60
    

    這個資訊清單會執行下列操作:

    • 將擴充期間的備用資源數量上限設為 50
    • 將縮減期間的執行個體數量下限設為 5
    • 使用內建的 Kubernetes 指標來決定資源調度。在這個範例中,指標是 CPU 使用率,目標使用率為 60%,可避免過度使用和使用不足。
  2. 將資訊清單套用至叢集:

    kubectl apply -f extras/postgres-hpa/hpa/userservice.yaml
    

為前端部署項目設定自動調度資源功能

  1. 查看 Deployment 的 HorizontalPodAutoscaler資訊清單:userservice

    # Copyright 2022 Google LLC
    #
    # Licensed under the Apache License, Version 2.0 (the "License");
    # you may not use this file except in compliance with the License.
    # You may obtain a copy of the License at
    #
    #      http://www.apache.org/licenses/LICENSE-2.0
    #
    # Unless required by applicable law or agreed to in writing, software
    # distributed under the License is distributed on an "AS IS" BASIS,
    # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    # See the License for the specific language governing permissions and
    # limitations under the License.
    
    ---
    apiVersion: autoscaling/v2
    kind: HorizontalPodAutoscaler
    metadata:
      name: frontend
    spec:
      behavior:
        scaleUp:
          stabilizationWindowSeconds: 0
          policies:
            - type: Percent
              value: 100
              periodSeconds: 5
          selectPolicy: Max
      scaleTargetRef:
        apiVersion: apps/v1
        kind: Deployment
        name: frontend
      minReplicas: 5
      maxReplicas: 25
      metrics:
        - type: External
          external:
            metric:
              name: loadbalancing.googleapis.com|https|request_count
              selector:
                matchLabels:
                  resource.labels.forwarding_rule_name: FORWARDING_RULE_NAME
            target:
              type: AverageValue
              averageValue: "5"
    

    這份資訊清單使用下列欄位:

    • spec.scaleTargetRef:要擴充的 Kubernetes 資源。
    • spec.minReplicas:備用資源數量下限,在本範例中為 5
    • spec.maxReplicas:副本數量上限,在本範例中為 25
    • spec.metrics.*:要使用的指標。在本範例中,這是每秒的 HTTP 要求數,也就是您部署的介面卡提供的 Cloud Monitoring 自訂指標。
    • spec.metrics.external.metric.selector.matchLabels:自動調度資源時要篩選的特定資源標籤。
  2. 找出從負載平衡器到 frontend Deployment 的轉送規則名稱:

    export FW_RULE=$(kubectl get ingress frontend -o=jsonpath='{.metadata.annotations.ingress\.kubernetes\.io/forwarding-rule}')
    echo $FW_RULE
    

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

    k8s2-fr-j76hrtv4-default-frontend-wvvf7381
    
  3. 在資訊清單中新增轉送規則:

    sed -i "s/FORWARDING_RULE_NAME/$FW_RULE/g" "extras/postgres-hpa/hpa/frontend.yaml"
    

    這個指令會將 FORWARDING_RULE_NAME 替換為您儲存的轉送規則。

  4. 將資訊清單套用至叢集:

    kubectl apply -f extras/postgres-hpa/hpa/frontend.yaml
    

檢查點:驗證自動調度資源設定

取得 HorizontalPodAutoscaler 資源的狀態:

kubectl get hpa

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

NAME                     REFERENCE                            TARGETS             MINPODS   MAXPODS   REPLICAS   AGE
accounts-db-postgresql   StatefulSet/accounts-db-postgresql   10905m/15 (avg)     1         5         2          5m2s
contacts                 Deployment/contacts                  1%/70%              1         5         1          11m
frontend                 Deployment/frontend                  <unknown>/5 (avg)   5         25        1          34s
userservice              Deployment/userservice               0%/60%              5         50        5          4m56s

到目前為止,您已設定應用程式並完成自動調度資源設定。前端和資料庫現在可以根據您提供的指標進行調度。

模擬負載並觀察 GKE 資源調度

Bank of Anthos 包含 loadgenerator 服務,可讓您模擬流量,測試應用程式在負載下的擴縮作業。在本節中,您將部署 loadgenerator 服務、產生負載,並觀察產生的擴縮作業。

部署負載測試產生器

  1. 建立環境變數,其中包含 Bank of Anthos 負載平衡器的 IP 位址:

    export LB_IP=$(kubectl get ingress frontend -o=jsonpath='{.status.loadBalancer.ingress[0].ip}')
    echo $LB_IP
    

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

    203.0.113.9
    
  2. 將負載平衡器的 IP 位址新增至資訊清單:

    sed -i "s/FRONTEND_IP_ADDRESS/$LB_IP/g" "extras/postgres-hpa/loadgenerator.yaml"
    
  3. 將資訊清單套用至叢集:

    kubectl apply -f  extras/postgres-hpa/loadgenerator.yaml
    

載入產生器會開始每秒新增一位使用者,最多可新增 250 位使用者。

模擬負載

在本節中,您會使用負載產生器模擬流量尖峰,並觀察副本數量和節點數量隨著時間增加,以因應負載增加的情況。接著結束測試,並觀察副本和節點數量因應而減少。

  1. 在本機公開負載產生器網頁介面:

    kubectl port-forward svc/loadgenerator 8080
    

    如果看到錯誤訊息,請在 Pod 執行時重試。

  2. 在瀏覽器中開啟負載產生器網頁介面。

    • 如果您使用本機殼層,請開啟瀏覽器並前往 http://127.0.0.1:8080。
    • 如果您使用 Cloud Shell,請按一下 「Web preview」(網頁預覽),然後按一下「Preview on port 8080」(透過以下通訊埠預覽:8080)
  3. 按一下「圖表」分頁標籤,即可查看一段時間內的成效。

  4. 開啟新的終端機視窗,然後監控水平 Pod 自動配置器的副本數量:

    kubectl get hpa -w
    

    負載增加時,備用資源數量也會增加。擴充作業大約需要十分鐘。

    NAME                     REFERENCE                            TARGETS          MINPODS   MAXPODS   REPLICAS
    accounts-db-postgresql   StatefulSet/accounts-db-postgresql   8326m/15 (avg)   1         5         5
    contacts                 Deployment/contacts                  51%/70%          1         5         2
    frontend                 Deployment/frontend                  5200m/5 (avg)    5         25        13
    userservice              Deployment/userservice               71%/60%          5         50        17
    
  5. 開啟另一個終端機視窗,然後檢查叢集中的節點數量:

    gcloud container clusters list \
        --filter='name=bank-of-anthos' \
        --format='table(name, currentMasterVersion, currentNodeVersion, currentNodeCount)' \
        --region="us-central1"
    
  6. 節點數量從三個增加,以容納新的副本。

  7. 開啟負載產生器介面,然後按一下「停止」結束測試。

  8. 再次檢查副本數量和節點數量,並觀察數字是否隨著負載減少而降低。縮減作業可能需要一段時間,因為 Kubernetes HorizontalPodAutoscaler 資源中副本的預設穩定時間範圍為五分鐘。詳情請參閱「穩定期」。

清除所用資源

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

刪除個別資源

Google Cloud 會根據您建立的 Kubernetes 物件建立負載平衡器等資源。如要刪除本教學課程中的所有資源,請執行下列步驟:

  1. 刪除 Kubernetes 範例資源:

    kubectl delete \
        -f extras/postgres-hpa/loadgenerator.yaml \
        -f extras/postgres-hpa/hpa \
        -f extras/postgres-hpa/kubernetes-manifests \
        -f extras/jwt/jwt-secret.yaml \
        -f https://raw.githubusercontent.com/GoogleCloudPlatform/k8s-stackdriver/master/custom-metrics-stackdriver-adapter/deploy/production/adapter.yaml
    
  2. 刪除 PostgreSQL 資料庫:

    helm uninstall accounts-db
    kubectl delete pvc -l "app.kubernetes.io/instance=accounts-db"
    kubectl delete configmaps initdb
    
  3. 刪除 GKE 叢集和 IAM 服務帳戶:

    gcloud iam service-accounts delete "bank-of-anthos@PROJECT_ID.iam.gserviceaccount.com" --quiet
    gcloud container clusters delete "bank-of-anthos" --region="us-central1" --quiet
    

刪除專案

    Delete a Google Cloud project:

    gcloud projects delete PROJECT_ID

後續步驟