設定水平自動調度 Pod 資源

本頁面說明如何在 Google Kubernetes Engine (GKE) 中,使用資源分配、負載平衡器流量、自訂指標或多個指標等指標,自動調整資源來擴充部署作業。本頁面也提供逐步操作說明,引導您設定 HorizontalPodAutoscaler (HPA) 設定檔,包括如何查看、刪除、清除及排解 HPA 物件問題。Deployment 是 Kubernetes API 物件,可讓您執行多個 Pod 副本,這些副本會分散在叢集的節點中。

本頁面適用於在 GKE 中管理應用程式資源調度,並想瞭解如何透過水平自動調度 Pod 資源,動態最佳化效能並維持成本效益的開發人員和操作人員。如要進一步瞭解內容中提及的常見角色和範例工作 Google Cloud,請參閱「常見的 GKE 使用者角色和工作」。

事前準備

開始之前,請務必先完成下列工作:

  • 啟用 Google Kubernetes Engine API。
  • 啟用 Google Kubernetes Engine API
  • 如要使用 Google Cloud CLI 執行這項工作,請安裝並初始化 gcloud CLI。如果您先前已安裝 gcloud CLI,請執行 gcloud components update 指令,取得最新版本。較舊的 gcloud CLI 版本可能不支援執行本文件中的指令。

HorizontalPodAutoscaler 物件的 API 版本

使用 Google Cloud 控制台時,系統會透過 autoscaling/v2 API 建立 HPA 物件。系統仍支援 autoscaling/v1 API,但不再建議使用,且不支援某些功能,例如使用 HPA 從零開始擴充及擴充至零。

建立 Deployment 範例

建立 HPA 物件前,必須先建立要監控的工作負載。本頁面的範例會將不同的 HPA 設定套用至下列 nginx Deployment。不同的範例會依據資源使用率、自訂或外部指標,以及多項指標來顯示 HPA。

將下列內容儲存至名為 nginx.yaml 的檔案:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
  namespace: default
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.7.9
        ports:
        - containerPort: 80
        resources:
          # You must specify requests for CPU to autoscale
          # based on CPU utilization
          requests:
            cpu: "250m"

此資訊清單指定了 CPU 要求數的值。如要依據資源的使用率百分比自動調度資源,您必須指定該資源的要求數。如果未指定要求,您只能根據資源使用率的絕對值自動調度資源,例如 CPU 使用率的毫 CPU。

如要建立 Deployment,請套用 nginx.yaml 資訊清單:

kubectl apply -f nginx.yaml

Deployment 已將 spec.replicas 設為 3,表示會部署三個 Pod。 您可以使用 kubectl get deployment nginx 指令進行驗證。

本頁的每個範例都會將不同的 HPA 物件套用至範例 nginx Deployment。

依據資源使用率自動調度資源

這個範例會建立 HPA 物件,在 CPU 使用率超過 50% 時自動調度nginx Deployment,並確保副本數量一律介於 1 到 10 之間。

您可以使用 Google Cloud 控制台、kubectl apply 指令,或僅針對平均 CPU 使用率使用 kubectl autoscale 指令,建立以 CPU 為目標的 HPA。

控制台

  1. 前往 Google Cloud 控制台的「Workloads」(工作負載) 頁面。

    前往「Workloads」(工作負載)

  2. 按一下 nginx Deployment 的名稱。

  3. 依序點選「動作」>「編輯自動調度資源」。

  4. 在「水平自動調度 Pod 資源」部分下方,按一下「選取並設定」。

  5. 指定下列值:

    • 副本數量下限:1
    • 副本數量上限:10
    • 自動調度資源指標:CPU
    • 目標:50
    • 單位:CPU
  6. 按一下「提交」。

kubectl apply

將下列 YAML 資訊清單儲存為名為 nginx-hpa.yaml 的檔案:

apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: nginx
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: nginx
  # Set the minimum and maximum number of replicas the Deployment can scale to.
  minReplicas: 1
  maxReplicas: 10
  metrics:
  - type: Resource
    resource:
      # The target average CPU utilization percentage across all Pods.
      name: cpu
      target:
        type: Utilization
        averageUtilization: 50

如果您建立資訊清單來配合自己專案中的特定詳細資料,請確保水平 Pod 自動調整器欄位中不含私密資料。

如要建立 HPA,請使用下列指令套用資訊清單:

kubectl apply -f nginx-hpa.yaml

kubectl autoscale

如要建立僅以平均 CPU 使用率為目標的 HPA 物件,可以使用 kubectl autoscale 指令:

kubectl autoscale deployment nginx --cpu-percent=50 --min=1 --max=10

如要取得叢集中的 HPA 清單,請使用下列指令:

kubectl get hpa

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

NAME    REFERENCE          TARGETS   MINPODS   MAXPODS   REPLICAS   AGE
nginx   Deployment/nginx   0%/50%    1         10        3          61s

如要取得 HPA 的詳細資料,可以使用 Google Cloud 控制台或 kubectl 指令。

控制台

  1. 前往 Google Cloud 控制台的「Workloads」(工作負載) 頁面。

    前往「Workloads」(工作負載)

  2. 按一下 nginx Deployment 的名稱。

  3. 按一下「Scaling」(縮放) 分頁標籤。

kubectl get

如要取得 HPA 的詳細資料,可以使用 kubectl get hpa 和 -o yaml 標記。status 欄位中包含目前備用資源數和所有最新的自動調度資源事件等相關資訊。

kubectl get hpa nginx -o yaml

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

apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  annotations:
    kubectl.kubernetes.io/last-applied-configuration: |
      {"apiVersion":"autoscaling/v2","kind":"HorizontalPodAutoscaler","metadata":{"annotations":{},"name":"nginx","namespace":"default"},"spec":{"maxReplicas":10,"metrics":[{"resource":{"name":"cpu","target":{"averageUtilization":50,"type":"Utilization"}},"type":"Resource"}],"minReplicas":1,"scaleTargetRef":{"apiVersion":"apps/v1","kind":"Deployment","name":"nginx"}}}
  creationTimestamp: "2025-10-30T19:42:43Z"
  name: nginx
  namespace: default
  resourceVersion: "220050"
  selfLink: /apis/autoscaling/v2/namespaces/default/horizontalpodautoscalers/nginx
  uid: 70d1067d-fb4d-11e9-8b2a-42010a8e013f
spec:
  maxReplicas: 10
  minReplicas: 1
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: nginx
  metrics:
  - type: Resource
    resource:
      name: cpu
      target:
        type: Utilization
        averageUtilization: 50
status:
  conditions:
  - lastTransitionTime: "2025-10-30T19:42:59Z"
    message: recent recommendations were higher than current one, applying the highest recent recommendation
    reason: ScaleDownStabilized
    status: "True"
    type: AbleToScale
  - lastTransitionTime: "2025-10-30T19:42:59Z"
    message: the HPA was able to successfully calculate a replica count from cpu resource utilization (percentage of request)
    reason: ValidMetricFound
    status: "True"
    type: ScalingActive
  - lastTransitionTime: "2025-10-30T19:42:59Z"
    message: the desired count is within the acceptable range
    reason: DesiredWithinRange
    status: "False"
    type: ScalingLimited
  currentMetrics:
  - type: Resource
    resource:
      name: cpu
      current:
        averageUtilization: 0
        averageValue: "0"
  currentReplicas: 3
  desiredReplicas: 3

如果您建立資訊清單來配合自己專案中的特定詳細資料,請確保水平 Pod 自動調整器欄位中不含私密資料。

請先刪除 HPA,再按照本頁其餘範例操作:

kubectl delete hpa nginx

刪除 HPA 物件時,Deployment 的副本數量會維持不變。部署作業不會自動還原為套用 HPA 前的狀態。

您可以進一步瞭解刪除 HPA 的相關資訊。

依據自訂或或外部指標自動調度資源

工作負載發出的任何指標,或可從外部來源查詢的指標,都可用於自動調度資源。GKE 內建支援功能,在許多情況下可根據自訂指標和外部指標自動調度資源,而 Kubernetes 支援其他指標轉接器,例如 KEDA 和 Prometheus 轉接器。

根據負載平衡器流量自動調度資源

GKE 的流量型自動調度資源功能,可整合負載平衡器的流量使用率信號,自動調度 Pod 資源。

使用流量做為自動調度資源信號可能很有幫助,因為流量是負載的領先指標,可與 CPU 和記憶體互補。內建與 GKE 的整合功能可確保設定程序簡單明瞭,且自動調度資源機制能迅速因應流量尖峰,滿足需求。

流量型自動調度功能由閘道控制器及其全域流量管理功能啟用。詳情請參閱「依據流量自動調度資源」。

根據負載平衡器流量自動調度資源的功能,僅適用於閘道工作負載。

需求條件

如要使用以流量為準的自動調度資源功能,必須符合下列條件:

  • 適用於 GKE 1.31 以上版本。
  • 專案已啟用 Gateway API。
  • 支援透過 Gateway API 部署的負載平衡器,以及 gke-l7-global-external-managed、gke-l7-regional-external-managed、gke-l7-rilb 或 gke-l7-gxlb GatewayClass 傳輸的流量。

限制

根據流量自動調度資源有下列限制:

  • 多叢集 GatewayClass (gke-l7-global-external-managed-mc、gke-l7-regional-external-managed-mc、gke-l7-rilb-mc 和 gke-l7-gxlb-mc) 不支援。
  • 不支援使用 LoadBalancer 類型服務的流量。
  • 參與流量自動調度機制的元件之間,必須有明確且獨立的關係。一個 HPA 物件必須專用於擴展單一 Deployment (或任何可擴展的資源),並由單一 Service 公開。
  • 使用 maxRatePerEndpoint 欄位設定 Service 的容量後,請預留足夠的時間 (通常為一分鐘,但在大型叢集中可能需要長達 15 分鐘),讓負載平衡器更新這項變更,然後再使用流量指標設定 HPA。這種做法可確保服務不會暫時發生以下情況:叢集嘗試根據負載平衡器發出的指標自動調度資源,但負載平衡器仍在設定中。
  • 如果多個負載平衡器 (例如 Ingress 和 Gateway,或兩個 Gateway) 為某項服務提供服務,且該服務使用以流量為準的自動調度功能,HPA 可能會根據個別負載平衡器的最高流量值做出調度決策,而不是根據所有負載平衡器的流量值總和。

部署以流量為準的自動調度資源功能

下列練習會使用 HPA,根據收到的流量自動調度 store-autoscale 部署作業的資源。閘道會接受來自網際網路的 Pod 傳入流量。自動調度器會比較 Gateway 的流量信號與 store-autoscale Service 資源上設定的每個 Pod 的流量容量。產生流量至閘道,會影響部署的 Pod 數量。

下圖說明以流量為準的自動調度機制運作方式:

HorizontalPodAutoscaler 根據流量調度 Deployment 資源。

如要部署以流量為準的自動調度資源功能,請按照下列步驟操作:

  1. 如果是標準叢集,請確認叢集已安裝 GatewayClass。如果是 Autopilot 叢集,系統預設會安裝 GatewayClass。

    kubectl get gatewayclass
    

    輸出內容會確認 GKE GatewayClass 資源已可在叢集中使用:

    NAME                               CONTROLLER                  ACCEPTED   AGE
    gke-l7-global-external-managed     networking.gke.io/gateway   True       16h
    gke-l7-regional-external-managed   networking.gke.io/gateway   True       16h
    gke-l7-gxlb                        networking.gke.io/gateway   True       16h
    gke-l7-rilb                        networking.gke.io/gateway   True       16h
    

    如果沒有看到這項輸出內容,請在 GKE 叢集中啟用 Gateway API。

  2. 將範例應用程式和閘道負載平衡器部署至叢集:

    kubectl apply -f https://raw.githubusercontent.com/GoogleCloudPlatform/gke-networking-recipes/master/gateway/docs/store-autoscale.yaml
    

    範例應用程式會建立:

    • 有 2 個副本的 Deployment。
    • 服務已啟用相關的「GCPBackendPolicy」設定 maxRatePerEndpoint 並設為「10」。如要進一步瞭解 Gateway 功能,請參閱「GatewayClass 功能」。
    • 可透過網際網路存取應用程式的外部閘道。 如要進一步瞭解如何使用閘道負載平衡器,請參閱「部署閘道」。
    • HTTPRoute 會比對所有流量,並將流量傳送至 store-autoscale 服務。

    使用以流量為準的自動調度資源時,「服務容量」是重要元素,因為這項設定會決定觸發自動調度資源事件的每個 Pod 流量。如要設定,請使用與 Service 相關聯的 GCPBackendPolicy 上的 maxRatePerEndpoint 欄位,定義 Service 應接收的流量上限 (以每秒每 Pod 的要求數為單位)。服務容量因應用程式而異。

    詳情請參閱「判斷服務容量」。

  3. 將下列資訊清單儲存為 hpa.yaml:

    apiVersion: autoscaling/v2
    kind: HorizontalPodAutoscaler
    metadata:
      name: store-autoscale
    spec:
      scaleTargetRef:
        apiVersion: apps/v1
        kind: Deployment
        name: store-autoscale
      # Set the minimum and maximum number of replicas the Deployment can scale to.
      minReplicas: 1
      maxReplicas: 10
      # This section defines that scaling should be based on the fullness of load balancer
      # capacity, using the following configuration.
      metrics:
      - type: Object
        object:
          describedObject:
            kind: Service
            name: store-autoscale
          metric:
            # The name of the custom metric which measures how "full" a backend is
            # relative to its configured capacity.
            name: "autoscaling.googleapis.com|gclb-capacity-fullness"
          target:
            # The target average value for the metric. The autoscaler adjusts the number
            # of replicas to maintain an average capacity fullness of 70% across all Pods.
            averageValue: 70
            type: AverageValue
    

    這個資訊清單描述了具有下列屬性的 HPA 物件:

    • minReplicas 和 maxReplicas:設定這個 Deployment 的副本數量下限和上限。在這個設定中,Pod 數量可從 1 個擴充至 10 個副本 (如果您使用 HPA 將擴充範圍設為零,則為 0 個副本)。
    • describedObject.name: store-autoscale:store-autoscale 服務的參照,用於定義流量容量。
    • scaleTargetRef.name: store-autoscale:store-autoscale Deployment 的參照,定義由 HPA 擴充的資源。
    • averageValue: 70:目標平均值為 70% 的容量使用率。這會為 HPA 提供成長空間,讓執行中的 Pod 可以在建立新 Pod 時處理多餘流量。

    如果您建立資訊清單來配合自己專案中的特定詳細資料,請確保水平 Pod 自動調整器欄位中不含私密資料。

水平 Pod 自動配置器會導致下列流量行為:

  • Pod 數量會調整為 1 到 10 個副本,以達到每個端點 70% 的最高速率。當 maxRatePerEndpoint=10 時,每個 Pod 的 RPS 為 7。
  • 如果每個 Pod 的 RPS 超過 7,Pod 就會擴充,直到達到 10 個副本的上限,或每個 Pod 的平均流量為 7 RPS。
  • 如果流量減少,Pod 會使用 HPA 演算法,將規模縮減至合理比率。

您也可以部署流量產生器,驗證以流量為依據的自動調度資源行為。

在 30 RPS 時,Deployment 會擴充至 5 個副本,因此每個副本在理想情況下會收到 6 RPS 的流量,也就是每個 Pod 的使用率為 60%。這低於 70% 的目標使用率,因此 Pod 會適當縮減。視流量波動情況而定,自動調整資源配置的副本數量也可能會波動。如要進一步瞭解副本數量的計算方式,請參閱「自動調度資源行為」。

依據多個指標自動調度資源

這個範例會建立 HPA 物件,根據 CPU 使用率和名為 packets_per_second 的自訂指標自動調度資源。

如果您按照先前的範例操作,且仍有名為 nginx 的 HPA 物件,請刪除該物件,再按照這個範例操作。

這個範例需要執行 apiVersion: autoscaling/v2。如要進一步瞭解可用的 API,請參閱適用於 HPA 物件的 API 版本。

將這個 YAML 資訊清單儲存為名為 nginx-multiple.yaml 的檔案:

apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: nginx
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: nginx
  minReplicas: 1
  maxReplicas: 10
  metrics: # The metrics to base the autoscaling on.
  - type: Resource
    resource:
      name: cpu # Scale based on CPU utilization.
      target:
        type: Utilization
        averageUtilization: 50
        # The HPA will scale the replicas to try and maintain an average
        # CPU utilization of 50% across all Pods.
  - type: Resource
    resource:
      name: memory # Scale based on memory usage.
      target:
        type: AverageValue
        averageValue: 100Mi
        # The HPA will scale the replicas to try and maintain an average
        # memory usage of 100 Mebibytes (MiB) across all Pods.
  # Uncomment these lines if you create the custom packets_per_second metric and
  # configure your app to export the metric.
  # - type: Pods
  #   pods:
  #     metric:
  #       name: packets_per_second
  #     target:
  #       type: AverageValue
  #       averageValue: 100

如果您建立資訊清單來配合自己專案中的特定詳細資料,請確保水平 Pod 自動調整器欄位中不含私密資料。

套用此 YAML 資訊清單:

kubectl apply -f nginx-multiple.yaml

建立完成後,水平 Pod 自動配置器會監控 nginx Deployment 的平均 CPU 用量、平均記憶體用量,以及 (如果您取消註解) 自訂packets_per_second指標。HPA 會根據值會產生較大自動調度資源事件的指標,自動調度 Deployment。

將數量縮減為零,以及從零開始擴充

從 GKE 1.37 版開始,您可以設定 HPA,在沒有工作負載需求時將 Deployment 縮減至零個副本 (0),並在需求增加時自動擴大。從零開始擴充時,GKE 會略過標準指標容許度檢查,立即啟動 Pod。

如要使用 HPA 設定縮減至零和從零擴充,請按照下列步驟操作:

  1. 確認叢集搭載 GKE 1.37 以上版本。
  2. 使用 AutoscalingMetric 資源設定至少一個自訂或外部指標。
  3. 在採用 autoscaling/v2 API 的 HPA 資訊清單中,設定 minReplicas: 0 欄位值組合。

如需逐步說明,請參閱「使用 HPA 將 GKE 工作負載資源調度至零或從零調度」。

設定最高效能 HPA 設定檔

效能 HPA 設定檔可縮短水平自動調度 Pod 資源的反應時間,有助於提升 HPA 處理大量物件的能力 (在 1.31 至 1.32 子版本中最多可處理 1,000 個物件,在 1.33 以上版本中最多可處理 5,000 個物件)。

如果 Autopilot 叢集的控制層搭載 GKE 1.32 以上版本,系統會自動啟用這個設定檔。如果是標準叢集,只要控制層執行 GKE 1.33 以上版本,系統就會自動在符合資格的叢集上啟用設定檔。

如果標準叢集符合下列所有條件,即可免除自動啟用 Performance HPA 設定檔:

  • 叢集要從舊版升級至 1.33 以上版本。
  • 叢集至少有一個節點集區,且具備下列任一機器類型:e2-micro、e2-custom-micro、g1-small、f1-micro。
  • 未啟用自動佈建節點功能。

如果現有叢集符合需求,您也可以啟用 Performance HPA 設定檔。

需求條件

如要啟用 Performance HPA 設定檔,請確認 Autopilot 和 Standard 叢集符合下列需求:

啟用 Performance HPA 設定檔

如要在叢集中啟用 Performance HPA 設定檔,請使用下列指令:

gcloud container clusters update CLUSTER_NAME \
    --location=LOCATION \
    --project=PROJECT_ID \
    --hpa-profile=performance

更改項目:

  • CLUSTER_NAME:叢集名稱。
  • LOCATION:叢集的運算可用區或區域 (例如 us-central1-a 或 us-central1)。
  • PROJECT_ID: Google Cloud 專案 ID。

停用 Performance HPA 設定檔

如要在叢集中停用 Performance HPA 設定檔,請使用下列指令:

gcloud container clusters update CLUSTER_NAME \
    --location=LOCATION \
    --project=PROJECT_ID \
    --hpa-profile=none

更改項目:

  • CLUSTER_NAME:叢集名稱。
  • LOCATION:叢集的運算可用區或區域 (例如 us-central1-a 或 us-central1)。
  • PROJECT_ID: Google Cloud 專案 ID。

查看 HorizontalPodAutoscaler 的詳細資料

如要查看 HPA 的設定和統計資料,請使用下列指令:

kubectl describe hpa HPA_NAME

將 HPA_NAME 替換為 HPA 物件名稱。

每個 HPA 物件的目前狀態都會顯示在 Conditions 欄位中,而自動調整大小事件則會列在 Events 欄位中。

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

Name:                                                  nginx
Namespace:                                             default
Labels:                                                <none>
Annotations:                                           kubectl.kubernetes.io/last-applied-configuration:
                                                         {"apiVersion":"autoscaling/v2","kind":"HorizontalPodAutoscaler","metadata":{"annotations":{},"name":"nginx","namespace":"default"},"s...
CreationTimestamp:                                     Tue, 05 May 2020 20:07:11 +0000
Reference:                                             Deployment/nginx
Metrics:                                               ( current / target )
  resource memory on pods:                             2220032 / 100Mi
  resource cpu on pods  (as a percentage of request):  0% (0) / 50%
Min replicas:                                          1
Max replicas:                                          10
Deployment pods:                                       1 current / 1 desired
Conditions:
  Type            Status  Reason              Message
  ----            ------  ------              -------
  AbleToScale     True    ReadyForNewScale    recommended size matches current size
  ScalingActive   True    ValidMetricFound    the HPA was able to successfully calculate a replica count from memory resource
  ScalingLimited  False   DesiredWithinRange  the desired count is within the acceptable range
Events:                                                <none>

刪除 HorizontalPodAutoscaler

您可以使用 Google Cloud 控制台或 kubectl delete 指令刪除 HPA 物件。

控制台

如要刪除 nginx HPA 物件,請按照下列步驟操作:

  1. 前往 Google Cloud 控制台的「Workloads」(工作負載) 頁面。

    前往「Workloads」(工作負載)

  2. 按一下 nginx Deployment 的名稱。

  3. 依序點選 「動作」>「自動調整規模」。

  4. 點選「刪除」。

kubectl delete

如要刪除 nginx HPA 物件,請使用下列指令:

kubectl delete hpa nginx

刪除 HPA 物件時,部署作業 (或其他部署物件) 會維持現有規模,不會還原為部署作業原始資訊清單中的副本數量。如要手動將 Deployment 調整回三個 Pod,則可以使用 kubectl scale 指令:

kubectl scale deployment nginx --replicas=3

清除所用資源

  1. 如果尚未刪除 HPA 物件,請執行下列指令:

    kubectl delete hpa nginx
    
  2. 刪除 nginx Deployment:

    kubectl delete deployment nginx
    
  3. 也可以選擇刪除叢集。

疑難排解

如需疑難排解建議,請參閱「排解水平自動調度 Pod 資源問題」。

後續步驟