使用政策設定閘道資源

本頁面說明如何設定 Google Kubernetes Engine (GKE) 在 GKE 叢集中部署閘道時建立的負載平衡器。

部署閘道時,GatewayClass 設定會決定 GKE 建立的負載平衡器。這個代管負載平衡器已預先設定預設設定,您可以使用政策修改。

您可以將政策附加至閘道、服務或 ServiceImport,自訂閘道資源,以符合基礎架構或應用程式需求。套用或修改政策後,閘道控制器會處理政策,並自動重新設定基礎負載平衡器資源。這樣就不需要刪除或重新建立閘道、路徑或服務資源。

您也可以使用 BackendTLSPolicy 設定後端驗證 TLS 設定,驗證閘道連線的後端身分 (搭配 HTTPRoute 使用 TLS 終止時)。詳情請參閱「設定後端 TLS」。如要使用 TLSRoute 將加密的 TLS 流量直接傳遞至後端,而不終止閘道的 TLS,請參閱「部署 TLS 傳遞閘道」。

事前準備

開始之前,請確認您已執行下列工作:

  • 啟用 Google Kubernetes Engine API。
  • 啟用 Google Kubernetes Engine API
  • 如要使用 Google Cloud CLI 執行這項工作,請安裝並初始化 gcloud CLI。如果您先前已安裝 gcloud CLI,請執行 gcloud components update 指令,取得最新版本。較舊的 gcloud CLI 版本可能不支援執行本文中的指令。
  • 確認您已有 Autopilot 或 Standard 叢集。如要建立新叢集,請參閱「建立 Autopilot 叢集」。

GKE Gateway 控制器需求

  • Gateway API 僅支援 VPC 原生叢集。
  • 如果使用區域性或跨區域 GatewayClass,則必須啟用僅限 Proxy 的子網路。
  • 叢集必須啟用 HttpLoadBalancing 外掛程式。
  • 如果您使用 Istio,必須將 Istio 升級至下列其中一個版本:
    • 1.15.2 以上版本
    • 1.14.5 以上版本
    • 1.13.9 以上版本。
  • 如果您使用 Shared VPC,則必須在主專案中,將 Compute Network User 角色指派給服務專案的 GKE 服務帳戶。

限制

除了 GKE Gateway 控制器的限制和限制之外,下列限制也適用於套用至閘道資源的政策:

  • GCPGatewayPolicy 資源只能附加至 gateway.networking.k8s.io 閘道。

  • GCPGatewayPolicy 資源必須與目標閘道位於相同的命名空間。

  • GKE Gateway 不支援階層式政策。

  • GCPBackendPolicy 不支援工作階段相依性的 HEADER_FIELD 或 HTTP_COOKIE 選項。如要設定 HEADER_FIELD 或 HTTP_COOKIE 工作階段相依性,請使用 GCPTrafficDistributionPolicy 資源。

  • 如果不同 GatewayClass 類型的閘道 (例如全域與區域、內部與外部,或代管與傳統版) 需要不相容的設定,請勿在這些閘道之間使用相同的後端服務。舉例來說,如果 GCPBackendPolicy 設定的功能不受「傳統」GatewayClass 支援,就無法套用至「傳統」閘道也使用的服務。為確保設定正確,請為每個需要不同政策設定的閘道建立專屬服務。

  • 使用 GCPTrafficDistributionPolicy 設定的工作階段相依性僅適用於單一叢集閘道。

  • GCPTrafficDistributionPolicy 工作階段相依性與 InferencePool 資源不相容,因為這些資源使用專屬的地區負載平衡演算法。

  • GCPTrafficDistributionPolicy 不支援為傳統版應用程式負載平衡器設定工作階段相依性或地區負載平衡政策。

  • 使用單一叢集閘道時,GCPBackendPolicy 和 HealthCheckPolicy 資源必須參照 Service 或 InferencePool 資源。

  • 使用多叢集閘道時,GCPBackendPolicy 和 HealthCheckPolicy 資源必須參照 ServiceImport 或 GCPInferencePoolImport 資源。

  • 在任何指定時間,每項通訊協定 (HTTP 或 TCP) 只能有一個 GCPBackendPolicy 附加至單一目標資源 (Service、ServiceImport、InferencePool 或 GCPInferencePoolImport)。Service 或 ServiceImport 可有一項 HTTP 政策 (HTTPRoute 後端的預設政策) 和一項 TCP 政策 (spec.protocol: TCP,適用於 TLSRoute 後端)。如果有多個 GCPBackendPolicy 資源使用相同通訊協定,且指定相同資源,系統會優先採用最舊的政策,不會附加較新的政策。

  • HealthCheckPolicy 和 GCPBackendPolicy 資源必須與目標 Service、ServiceImport、InferencePool 或 GCPInferencePoolImport 資源位於相同的命名空間。

  • GCPBackendPolicy 和 HealthCheckPolicy 資源只能指定單一資源 (例如 Service 或 InferencePool)。具有 spec.protocol: TCP 的 GCPBackendPolicy 只能指定 Service 和 ServiceImport 資源。

  • 透過 TLSRoute 使用 TLS 轉送時,請注意下列事項:

    • 不支援 BackendTLSPolicy、SSL 政策、Google Cloud Armor 安全性政策、IAP 和 CORS 篩選器。
    • 您可以將使用 TCP 或 SSL 檢查類型的 HealthCheckPolicy 和 GCPBackendPolicy,附加至 TLSRoute 參照的 Service 或 ServiceImport。
    • TLSRoute 後端 (Proxy 網路負載平衡器) 的 GCPBackendPolicy 必須將 spec.protocol 欄位設為 TCP 值 (如果沒有 spec.protocol 欄位,政策會預設為 HTTP 值,並套用至應用程式負載平衡器上的 HTTPRoute 後端)。
    • TCP 政策僅支援 spec.default 欄位中的下列欄位:timeoutSec、connectionDraining、logging.enabled、logging.sampleRate、sessionAffinity.type (有效值為 CLIENT_IP 或 NONE)、capacityScalerPercent、balancingMode: CONNECTION 和 maxConnectionsPerEndpoint。
    • 如果 TCP 政策指定 ServiceImport 資源,您可以在 spec.default.scopes 欄位中設定 capacityScalerPercent、balancingMode: CONNECTION 和 maxConnectionsPerEndpoint 欄位,而不是在 spec.default 欄位中設定。每個範圍都適用於與其 selector 欄位相符的後端,例如 gke.io/cluster-name、gke.io/zone 或 gke.io/region。
    • 如果 TCP 政策設定了 spec.default 欄位或範圍中的任何其他欄位,或 HTTP 政策設定了僅限 TCP 的欄位 (balancingMode: CONNECTION 或 maxConnectionsPerEndpoint),則系統會在建立時拒絕。
    • 詳情請參閱「部署 TLS 直通閘道」。

最佳做法:使用不同的 GatewayClass 為每個閘道建立不同的 Service,確保 Service 的政策與負載平衡器類型相容。

為區域性內部閘道設定全域存取權

本節說明的功能適用於搭載 1.24 以上版本的 GKE 叢集。

如要為內部閘道啟用全域存取權,請將政策附加至閘道資源。

下列 GCPGatewayPolicy 資訊清單會啟用區域性內部閘道,以便進行全域存取:

apiVersion: networking.gke.io/v1
kind: GCPGatewayPolicy
metadata:
  name: my-gateway-policy
  namespace: default
spec:
  default:
    # Enable global access for the regional internal Application Load Balancer.
    allowGlobalAccess: true
  targetRef:
    group: gateway.networking.k8s.io
    kind: Gateway
    name: my-gateway

設定多叢集閘道的區域

本節說明的功能適用於 1.30.3-gke.1225000 以上版本的 GKE 叢集。

如果機群中的叢集橫跨多個區域,您可能需要部署多個區域性閘道,以因應各種用途,例如跨區域備援、低延遲和資料主權。在多叢集閘道設定叢集中,您可以指定要部署區域閘道的區域。如未指定區域,預設區域會是設定叢集的區域。

如要為多叢集閘道設定區域,請使用 GCPGatewayPolicy 中的 region 欄位。在以下範例中,閘道是在 us-central1 區域中設定:

apiVersion: networking.gke.io/v1
kind: GCPGatewayPolicy
metadata:
  name: my-gateway-policy
  namespace: default
spec:
  default:
    region: us-central1
  targetRef:
    group: gateway.networking.k8s.io
    kind: Gateway
    name: my-regional-gateway

設定 SSL 政策,保護用戶端到負載平衡器的流量

本節說明 1.24 以上版本 GKE 叢集提供的功能。

如要保護用戶端到負載平衡器的流量,請在 GCPGatewayPolicy 中新增政策名稱,藉此設定 SSL 政策。根據預設,閘道並未定義及附加 SSL 政策。

請務必先建立 SSL 政策,再於 GCPGatewayPolicy 資源中參照該政策。

下列 GCPGatewayPolicy 資訊清單指定名為 gke-gateway-ssl-policy 的安全性政策:

apiVersion: networking.gke.io/v1
kind: GCPGatewayPolicy
metadata:
  name: my-gateway-policy
  namespace: team1
spec:
  default:
    sslPolicy: gke-gateway-ssl-policy
  targetRef:
    group: gateway.networking.k8s.io
    kind: Gateway
    name: my-gateway

設定健康狀態檢查

本節說明的功能適用於搭載 1.24 以上版本的 GKE 叢集。

根據預設,對於使用 HTTP 或 kubernetes.io/h2c 應用程式通訊協定的後端服務,HealthCheck 的類型為 HTTP。如果是 HTTPS 通訊協定,預設健康狀態檢查為 HTTPS 類型。如果是 HTTP2 通訊協定,預設健康狀態檢查為 HTTP2 類型。

您可以使用 HealthCheckPolicy 控制負載平衡器健康狀態檢查設定。每種健康狀態檢查 (http、https、grpc、http2 和 tcp) 都有可定義的參數。 Google Cloud 會為每個 GKE 服務的各項後端服務建立專屬健康狀態檢查。

如果健康狀態檢查路徑不是標準的「/」,您可能需要為負載平衡器設定自訂 HealthCheckPolicy,負載平衡器才能正常運作。如要調整健康狀態檢查參數,也必須進行這項設定。舉例來說,如果預設要求路徑是「/」,但您的服務無法透過該要求路徑存取,而是使用「/health」回報健康狀態,則您必須在 HealthCheckPolicy 中據此設定 requestPath。

如果 TLS 轉送後端使用 TLSRoute,請將健康狀態檢查類型設為 TCP 或 SSL (如果後端在獨立通訊埠上回應 HTTP 健康狀態檢查,則設為 HTTP 或 HTTPS)。HealthCheckPolicy 適用於使用目標 Service 的每個後端。如果 HTTPRoute 和 TLSRoute 都參照相同的服務,政策會設定這兩項路徑的健康狀態檢查,這可能會將其中一項路徑的後端標示為健康狀態不良。如要分別為各路徑設定健康狀態檢查,請為各路徑使用不同的 Service。詳情請參閱「部署 TLS 直通閘道」。

設定健康狀態檢查時,請注意下列限制:

  • 與 GKE Ingress 不同,GKE Gateway 不會根據 Pod 的 readiness 或 liveness 探測,自動推論健康狀態檢查參數 (例如路徑、通訊埠或通訊協定)。如果服務未在預設根路徑 (/) 傳回成功回應,您必須明確設定 HealthCheckPolicy。
  • Google Cloud 健康狀態檢查探測嚴格要求 HTTP 200 (OK) 回應代碼。如果應用程式在探測路徑上傳回重新導向 (例如 HTTP 301 或 302) 或用戶端錯誤 (例如已驗證端點上的 HTTP 401 或 403),負載平衡器會將後端標示為健康狀態不良,導致「No healthy upstream」錯誤。
  • 您無法在 GKE Gateway HealthCheckPolicy 探測中設定自訂 HTTP 要求標頭 (例如 Authorization 標頭)。如果後端需要驗證標頭,您必須設定應用程式,允許Google Cloud 健康狀態檢查 IP 範圍未經驗證即存取專屬健康狀態檢查路徑 (例如 /healthz 或 /ping)。

下列 HealthCheckPolicy 資訊清單顯示設定健康狀態檢查政策時可用的所有欄位:

服務

# Health check configuration for the load balancer. For more information
# about these fields, see https://docs.cloud.google.com/compute/docs/reference/rest/v1/healthChecks.
apiVersion: networking.gke.io/v1
kind: HealthCheckPolicy
metadata:
  name: lb-healthcheck
  namespace: lb-service-namespace
spec:
  default:
    checkIntervalSec: INTERVAL  # The default value is 15 seconds.
    timeoutSec: TIMEOUT
    healthyThreshold: HEALTHY_THRESHOLD
    unhealthyThreshold: UNHEALTHY_THRESHOLD
    logConfig:
      enabled: true
    config:
      type: PROTOCOL
      httpHealthCheck:
        portSpecification: PORT_SPECIFICATION
        port: PORT
        host: HOST
        requestPath: REQUEST_PATH
        response: RESPONSE
        proxyHeader: PROXY_HEADER
      httpsHealthCheck:
        portSpecification: PORT_SPECIFICATION
        port: PORT
        host: HOST
        requestPath: REQUEST_PATH
        response: RESPONSE
        proxyHeader: PROXY_HEADER
      grpcHealthCheck:
        grpcServiceName: GRPC_SERVICE_NAME
        portSpecification: PORT_SPECIFICATION
        port: PORT
      http2HealthCheck:
        portSpecification: PORT_SPECIFICATION
        port: PORT
        host: HOST
        requestPath: REQUEST_PATH
        response: RESPONSE
        proxyHeader: PROXY_HEADER
      tcpHealthCheck:
        portSpecification: PORT_SPECIFICATION
        port: PORT
        portName: PORT_NAME
        request: REQUEST
        response: RESPONSE
        proxyHeader: PROXY_HEADER
  # Attach to a Service in the cluster.
  targetRef:
    group: ""
    kind: Service
    name: lb-service

多叢集服務

apiVersion: networking.gke.io/v1
kind: HealthCheckPolicy
metadata:
  name: lb-healthcheck
  namespace: lb-service-namespace
spec:
  # The default and config fields control the health check configuration for the
  # load balancer. For more information about these fields, see
  # https://docs.cloud.google.com/compute/docs/reference/rest/v1/healthChecks.
  default:
    checkIntervalSec: INTERVAL
    timeoutSec: TIMEOUT
    healthyThreshold: HEALTHY_THRESHOLD
    unhealthyThreshold: UNHEALTHY_THRESHOLD
    logConfig:
      enabled: ENABLED
    config:
      type: PROTOCOL
      httpHealthCheck:
        portSpecification: PORT_SPECIFICATION
        port: PORT
        host: HOST
        requestPath: REQUEST_PATH
        response: RESPONSE
        proxyHeader: PROXY_HEADER
      httpsHealthCheck:
        portSpecification: PORT_SPECIFICATION
        port: PORT
        host: HOST
        requestPath: REQUEST_PATH
        response: RESPONSE
        proxyHeader: PROXY_HEADER
      grpcHealthCheck:
        grpcServiceName: GRPC_SERVICE_NAME
        portSpecification: PORT_SPECIFICATION
        port: PORT
      http2HealthCheck:
        portSpecification: PORT_SPECIFICATION
        port: PORT
        host: HOST
        requestPath: REQUEST_PATH
        response: RESPONSE
        proxyHeader: PROXY_HEADER
      tcpHealthCheck:
        portSpecification: PORT_SPECIFICATION
        port: PORT
        portName: PORT_NAME
        request: REQUEST
        response: RESPONSE
        proxyHeader: PROXY_HEADER
  # Attach to a multi-cluster Service by referencing the ServiceImport.
  targetRef:
    group: net.gke.io
    kind: ServiceImport
    name: lb-service

InferencePool

apiVersion: networking.gke.io/v1
kind: HealthCheckPolicy
metadata:
  name: lb-healthcheck
  namespace: lb-service-namespace
spec:
  default:
    checkIntervalSec: INTERVAL  # The default value is 15 seconds.
    timeoutSec: TIMEOUT
    healthyThreshold: HEALTHY_THRESHOLD
    unhealthyThreshold: UNHEALTHY_THRESHOLD
    logConfig:
      enabled: true
    config:
      type: PROTOCOL
      httpHealthCheck:
        portSpecification: PORT_SPECIFICATION
        port: PORT
        host: HOST
        requestPath: REQUEST_PATH
        response: RESPONSE
        proxyHeader: PROXY_HEADER
      httpsHealthCheck:
        portSpecification: PORT_SPECIFICATION
        port: PORT
        host: HOST
        requestPath: REQUEST_PATH
        response: RESPONSE
        proxyHeader: PROXY_HEADER
      grpcHealthCheck:
        grpcServiceName: GRPC_SERVICE_NAME
        portSpecification: PORT_SPECIFICATION
        port: PORT
      http2HealthCheck:
        portSpecification: PORT_SPECIFICATION
        port: PORT
        host: HOST
        requestPath: REQUEST_PATH
        response: RESPONSE
        proxyHeader: PROXY_HEADER
      tcpHealthCheck:
        portSpecification: PORT_SPECIFICATION
        port: PORT
        portName: PORT_NAME
        request: REQUEST
        response: RESPONSE
        proxyHeader: PROXY_HEADER
  # Attach to an InferencePool in the cluster.
  targetRef:
    group: inference.networking.k8s.io
    kind: InferencePool
    name: my-inference-pool

多叢集 InferencePool

apiVersion: networking.gke.io/v1
kind: HealthCheckPolicy
metadata:
  name: lb-healthcheck
  namespace: lb-service-namespace
spec:
  default:
    checkIntervalSec: INTERVAL
    timeoutSec: TIMEOUT
    healthyThreshold: HEALTHY_THRESHOLD
    unhealthyThreshold: UNHEALTHY_THRESHOLD
    logConfig:
      enabled: true
    config:
      type: PROTOCOL
      httpHealthCheck:
        portSpecification: PORT_SPECIFICATION
        port: PORT
        host: HOST
        requestPath: REQUEST_PATH
        response: RESPONSE
        proxyHeader: PROXY_HEADER
      httpsHealthCheck:
        portSpecification: PORT_SPECIFICATION
        port: PORT
        host: HOST
        requestPath: REQUEST_PATH
        response: RESPONSE
        proxyHeader: PROXY_HEADER
      grpcHealthCheck:
        grpcServiceName: GRPC_SERVICE_NAME
        portSpecification: PORT_SPECIFICATION
        port: PORT
      http2HealthCheck:
        portSpecification: PORT_SPECIFICATION
        port: PORT
        host: HOST
        requestPath: REQUEST_PATH
        response: RESPONSE
        proxyHeader: PROXY_HEADER
      tcpHealthCheck:
        portSpecification: PORT_SPECIFICATION
        port: PORT
        portName: PORT_NAME
        request: REQUEST
        response: RESPONSE
        proxyHeader: PROXY_HEADER
  # Attach to a multi-cluster InferencePool.
  targetRef:
    group: networking.gke.io
    kind: GCPInferencePoolImport
    name: my-inference-pool-import

更改下列內容:

  • INTERVAL:指定每個健康狀態檢查探測器的檢查時間間隔 (以秒為單位)。這是指從某個探測器開始檢查,到下一次檢查開始之間的時間。如省略這個參數,則在未指定 HealthCheckPolicy 時, Google Cloud 預設為 15 秒;如指定 HealthCheckPolicy 但未指定 checkIntervalSec 值,則預設為 5 秒。詳情請參閱「多個探測和頻率」。
  • TIMEOUT:指定Google Cloud 等待探測回應的時間長度。TIMEOUT 的值必須小於或等於 INTERVAL。單位為秒。每項探測都必須在探測逾時前,傳送 HTTP 200 (OK) 回應代碼。
  • HEALTHY_THRESHOLD 和 UNHEALTHY_THRESHOLD:指定至少一個探測器必須成功或失敗的連續連線嘗試次數,才能將健康狀態從健康變更為不健康,或從不健康變更為健康。如果省略其中一個參數, Google Cloud 預設值為 2。
  • PROTOCOL:指定探測系統用於健康狀態檢查的通訊協定。詳情請參閱「HTTP、HTTPS 和 HTTP/2 的成功標準」、「gRPC 的成功標準」和「TCP 的成功標準」。這是必要參數。
  • ENABLED:指定是否啟用記錄功能。
  • PORT_SPECIFICATION:指定健康狀態檢查是否使用固定通訊埠 (USE_FIXED_PORT)、命名通訊埠 (USE_NAMED_PORT) 或服務通訊埠 (USE_SERVING_PORT)。如未指定,健康狀態檢查會遵循 port 欄位中指定的行為。如未指定 port,這個欄位會預設為 USE_SERVING_PORT。
  • PORT:HealthCheckPolicy 僅支援使用通訊埠編號指定負載平衡器健康狀態檢查通訊埠。如果省略這個參數, Google Cloud 預設值為 80。由於負載平衡器會直接將探測傳送至 Pod 的 IP 位址,因此即使 targetPort 的 Service 參照了 containerPort,您也應選取與提供服務 Pod 的 containerPort 相符的通訊埠。您不限於使用 Service 的 targetPort 參照的 containerPorts。
  • HOST:健康狀態檢查要求中的主機標頭值。這個值採用主機名稱的 RFC 1123 定義,但不允許使用數字 IP 位址。如未指定或留空,這個值會預設為健康狀態檢查的 IP 位址。
  • REQUEST:指定建立 TCP 連線後要傳送的應用程式資料。如未指定,則預設值為空白。如果要求和回應皆為空白,則建立的連線本身即代表健康狀態良好。要求資料只能採用 ASCII 格式。
  • REQUEST_PATH:指定健康狀態檢查要求的 request-path。如未指定或留空,則預設為 /。
  • RESPONSE:指定要與回應資料開頭比對的位元組。如果未指定或留空,GKE 會將任何回應解讀為健康狀態良好。回應資料只能是 ASCII。
  • PROXY_HEADER:指定 Proxy 標頭類型。您可以使用 NONE 或 PROXY_V1。預設為 NONE。
  • GRPC_SERVICE_NAME:gRPC 服務的選用名稱。如要指定所有服務,請省略這個欄位。

如要進一步瞭解 HealthCheckPolicy 欄位,請參閱 healthChecks 參考資料。

設定 Cloud Armor 後端安全性政策,保護後端服務

本節說明的功能適用於搭載 1.24 以上版本的 GKE 叢集。

如要設定 Cloud Armor 後端安全性政策,請將安全性政策名稱新增至 GCPBackendPolicy,保護後端服務。根據預設,閘道並未定義及附加任何 Cloud Armor 後端安全性政策。

請務必先建立 Cloud Armor 後端安全性政策,再於 GCPBackendPolicy 中參照該政策。如要啟用區域性閘道,則必須建立區域性 Cloud Armor 後端安全性政策。

下列 GCPBackendPolicy 資訊清單指定名為 example-security-policy 的後端安全性政策:

服務

apiVersion: networking.gke.io/v1
kind: GCPBackendPolicy
metadata:
  name: my-backend-policy
  namespace: lb-service-namespace
spec:
  default:
    # Apply a Cloud Armor security policy.
    securityPolicy: example-security-policy
  # Attach to a Service in the cluster.
  targetRef:
    group: ""
    kind: Service
    name: lb-service

多叢集服務

apiVersion: networking.gke.io/v1
kind: GCPBackendPolicy
metadata:
  name: my-backend-policy
  namespace: lb-service-namespace
spec:
  default:
    # Apply a Cloud Armor security policy.
    securityPolicy: example-security-policy
  # Attach to a multi-cluster Service by referencing the ServiceImport.
  targetRef:
    group: net.gke.io
    kind: ServiceImport
    name: lb-service

InferencePool

apiVersion: networking.gke.io/v1
kind: GCPBackendPolicy
metadata:
  name: my-backend-policy
  namespace: lb-service-namespace
spec:
  default:
    securityPolicy: example-security-policy
  # Attach to an InferencePool in the cluster.
  targetRef:
    group: inference.networking.k8s.io
    kind: InferencePool
    name: my-inference-pool

多叢集 InferencePool

apiVersion: networking.gke.io/v1
kind: GCPBackendPolicy
metadata:
  name: my-backend-policy
  namespace: lb-service-namespace
spec:
  default:
    securityPolicy: example-security-policy
  # Attach to a multi-cluster InferencePool.
  targetRef:
    group: networking.gke.io
    kind: GCPInferencePoolImport
    name: my-inference-pool-import

設定 IAP

Identity-Aware Proxy (IAP) 會對與 HTTPRoute 相關聯的後端服務,強制執行存取控管政策。強制執行這項設定後,只有經過驗證的使用者或應用程式,且具備正確的身分與存取權管理 (IAM) 角色,才能存取這些後端服務。

根據預設,後端服務不會套用 IAP,您必須在 GCPBackendPolicy 中明確設定 IAP。

如要透過閘道設定 IAP,請按照下列步驟操作:

  1. 取得 OAuth 用戶端的用戶端 ID 和用戶端密鑰。用戶端密鑰僅在建立 OAuth 用戶端時可用。詳情請參閱「管理 OAuth 用戶端」。
  2. 啟用 GKE 的 IAP。

    您不需要建立 BackendConfig,因為 BackendConfig 是 Ingress 設定資源。

  3. 如要指定參照 Secret 的 IAP 政策,請按照下列步驟操作:

    1. 將下列 GCPBackendPolicy 資訊清單儲存為 backend-policy.yaml:

      服務

      apiVersion: networking.gke.io/v1
      kind: GCPBackendPolicy
      metadata:
        name: backend-policy
      spec:
        default:
          # IAP OAuth2 settings. For more information about these fields,
          # see https://docs.cloud.google.com/iap/docs/reference/rest/v1/IapSettings#oauth2.
          iap:
            enabled: true
            oauth2ClientSecret:
              name: CLIENT_SECRET
            clientID: CLIENT_ID
        # Attach to a Service in the cluster.
        targetRef:
          group: ""
          kind: Service
          name: SERVICE_NAME
      

      更改下列內容:

      • CLIENT_SECRET:OAuth 用戶端密鑰。
      • CLIENT_ID:OAuth 用戶端 ID。
      • SERVICE_NAME:GCPBackendPolicy 中要指定的 Service 名稱。

      多叢集服務

      apiVersion: networking.gke.io/v1
      kind: GCPBackendPolicy
      metadata:
        name: backend-policy
      spec:
        default:
          # IAP OAuth2 settings. For more information about these fields,
          # see https://docs.cloud.google.com/iap/docs/reference/rest/v1/IapSettings#oauth2.
          iap:
            enabled: true
            oauth2ClientSecret:
              name: CLIENT_SECRET
            clientID: CLIENT_ID
        # Attach to a multi-cluster Service by referencing the ServiceImport.
        targetRef:
          group: net.gke.io
          kind: ServiceImport
          name: SERVICEIMPORT_NAME
      

      更改下列內容:

      • CLIENT_SECRET:OAuth 用戶端密鑰。
      • CLIENT_ID:OAuth 用戶端 ID。
      • SERVICEIMPORT_NAME:GCPBackendPolicy 中要指定的 ServiceImport 名稱。
    2. 套用 backend-policy.yaml 資訊清單:

      kubectl apply -f backend-policy.yaml
      
  4. 驗證設定:

    1. 使用 IAP 建立 GCPBackendPolicy 後,請確認政策已套用:

      kubectl get gcpbackendpolicy
      

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

      NAME             AGE
      backend-policy   45m
      
    2. 如要取得更多詳細資料,請使用 describe 指令:

      kubectl describe gcpbackendpolicy
      

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

      Name:         backend-policy
      Namespace:    default
      Labels:       <none>
      Annotations:  <none>
      API Version:  networking.gke.io/v1
      Kind:         GCPBackendPolicy
      Metadata:
        Creation Timestamp:  2023-05-27T06:45:32Z
        Generation:          2
        Resource Version:    19780077
        UID:                 f4f60a3b-4bb2-4e12-8748-d3b310d9c8e5
      Spec:
        Default:
          Iap:
            Client ID:  441323991697-luotsrnpboij65ebfr13hlcpm5a4heke.apps.googleusercontent.com
            Enabled:    true
            oauth2ClientSecret:
              Name:  my-iap-secret
        Target Ref:
          Group:
          Kind:   Service
          Name:   lb-service
      Status:
        Conditions:
          Last Transition Time:  2023-05-27T06:48:25Z
          Message:
          Reason:                Attached
          Status:                True
          Type:                  Attached
      Events:
        Type     Reason  Age                 From                   Message
        ----     ------  ----                ----                   -------
        Normal   ADD     46m                 sc-gateway-controller  default/backend-policy
        Normal   SYNC    44s (x15 over 43m)  sc-gateway-controller  Application of GCPBackendPolicy "default/backend-policy" was a success
      

設定後端服務逾時

本節說明的功能適用於搭載 1.24 以上版本的 GKE 叢集。

下列 GCPBackendPolicy 資訊清單指定後端服務逾時時間為 40 秒。timeoutSec 欄位預設為 30 秒。

服務

apiVersion: networking.gke.io/v1
kind: GCPBackendPolicy
metadata:
  name: my-backend-policy
  namespace: lb-service-namespace
spec:
  default:
    # Backend service timeout, in seconds, for the load balancer. The default
    # value is 30.
    timeoutSec: 40
  # Attach to a Service in the cluster.
  targetRef:
    group: ""
    kind: Service
    name: lb-service

多叢集服務

apiVersion: networking.gke.io/v1
kind: GCPBackendPolicy
metadata:
  name: my-backend-policy
  namespace: lb-service-namespace
spec:
  default:
    timeoutSec: 40
  # Attach to a multi-cluster Service by referencing the ServiceImport.
  targetRef:
    group: net.gke.io
    kind: ServiceImport
    name: lb-service

InferencePool

apiVersion: networking.gke.io/v1
kind: GCPBackendPolicy
metadata:
  name: my-backend-policy
  namespace: lb-service-namespace
spec:
  default:
    timeoutSec: 40
  # Attach to an InferencePool in the cluster.
  targetRef:
    group: inference.networking.k8s.io
    kind: InferencePool
    name: my-inference-pool

多叢集 InferencePool

apiVersion: networking.gke.io/v1
kind: GCPBackendPolicy
metadata:
  name: my-backend-policy
  namespace: lb-service-namespace
spec:
  default:
    timeoutSec: 40
  # Attach to a multi-cluster InferencePool.
  targetRef:
    group: networking.gke.io
    kind: GCPInferencePoolImport
    name: my-inference-pool-import

使用 GCPBackendPolicy 設定後端選取

您可以在 GCPBackendPolicy 中,透過 CUSTOM_METRICS 平衡模式設定特定自訂指標,影響負載平衡器後端服務分配流量的方式。這個平衡模式會根據您定義的自訂指標,以及應用程式後端回報的指標,進行負載平衡。

詳情請參閱「使用以自訂指標為基礎的負載平衡進行流量管理」。

backends[] 欄位中的 customMetrics[] 陣列包含下列欄位:

  • name:指定使用者定義的自訂指標名稱。
  • maxUtilization::設定這項指標的目標或使用率上限。 有效範圍為 [0, 100]。
  • dryRun:布林值欄位。如果設為 true,指標資料會回報給 Cloud Monitoring,但不會影響負載平衡決策。

範例

下列範例顯示 GCPBackendPolicy 資訊清單,其中設定了後端選取和端點層級轉送的自訂指標。

  1. 將下列資訊清單儲存為 my-backend-policy.yaml:

    kind: GCPBackendPolicy
    apiVersion: networking.gke.io/v1
    metadata:
      name: my-backend-policy
      namespace: team-awesome
    spec:
      # Attach to the super-service Service.
      targetRef:
        kind: Service
        name: super-service
      default:
        backends:
        # Configuration for all locations.
        - location: "*"
          # Use the rate balancing mode for the load balancer.
          balancingMode: RATE
          # Maximum number of requests per second for each endpoint.
          maxRatePerEndpoint: 9000
        # Configuration for us-central1-a
        - location: us-central1-a
          # maxRatePerEndpoint: 9000 inherited from the * configuration.
          # Use the custom metrics balancing mode for the load balancer.
          balancingMode: CUSTOM_METRICS
          # Configure the custom metrics for the load balancer to use.
          customMetrics:
          - name: gpu-load
            maxUtilizationPercent: 100 # value ranges from 0 to 100 and maps to the floating point range [0.0, 1.0]
            dryRun: false
    
  2. 將資訊清單套用至叢集:

    kubectl apply -f my-backend-policy.yaml
    

負載平衡器會根據 RATE 平衡模式和自訂 gpu-load 指標分配流量。

使用 GCPTrafficDistributionPolicy 設定端點層級轉送

Google Kubernetes Engine (GKE) Gateway 中的 GCPTrafficDistributionPolicy API 提供進階流量管理功能,可精確控管流量如何分配至應用程式 Pod。這項統一的 GKE 原生資源可簡化負載平衡演算法和工作階段相依性設定的管理作業。

GCPTrafficDistributionPolicy 可讓您設定:

  • 負載平衡演算法:指定流量在後端端點之間的分配方式。

    • WEIGHTED_ROUND_ROBIN:選取這個演算法時,負載平衡器會使用自訂指標計算權重,並根據這些報表指標分配流量。GCPTrafficDistributionPolicy 設定中的 customMetrics[] 陣列包含下列欄位:

      • name:指定使用者定義的自訂指標名稱。
      • dryRun:如果設為 true,指標資料會回報至 Cloud Monitoring,但不會影響負載平衡。
  • RING_HASH:這個演算法適用於對快取效能敏感的服務。這項演算法採用一致性雜湊,在新增或移除後端 Pod 時,盡可能減少要求重新對應,確保擴充事件期間的穩定性。設定 minimumHashRingSize 欄位可更精細地分配負載。

  • 工作階段相依性:確保來自相同用戶端的要求一律轉送至相同的後端 Pod。這對有狀態工作負載 (例如電子商務購物車或遊戲工作階段) 來說至關重要。GKE Gateway 使用 GCPTrafficDistributionPolicy,支援 Google Cloud應用程式負載平衡器執行個體上可用的所有工作階段相依性類型,包括 STRONG_COOKIE_AFFINITY、HEADER_FIELD、HTTP_COOKIE、GENERATED_COOKIE 和 CLIENT_IP。

詳情請參閱「使用以自訂指標為基礎的負載平衡進行流量管理」。

範例

以下範例顯示 GCPTrafficDistributionPolicy 資訊清單,該資訊清單使用 WEIGHTED_ROUND_ROBIN 負載平衡演算法和自訂指標,設定端點層級轉送。

  1. 將下列資訊清單範例儲存為 GCPTrafficDistributionPolicy.yaml:

    apiVersion: networking.gke.io/v1
    kind: GCPTrafficDistributionPolicy
    metadata:
      name: echoserver-v2
      namespace: team1
    spec:
      targetRefs:
      # Attach to the echoserver-v2 Service in the cluster.
      - kind: Service
        group: ""
        name: echoserver-v2
      default:
        # Use custom metrics to distribute traffic across endpoints.
        localityLbAlgorithm: WEIGHTED_ROUND_ROBIN
        # Configure metrics from an ORCA load report to use for traffic
        # distribution.
        customMetrics:
        - name: orca.named_metrics.bescm11
          dryRun: false
        - name: orca.named_metrics.bescm12
          dryRun: true
    
  2. 將資訊清單套用至叢集:

    kubectl apply -f GCPTrafficDistributionPolicy.yaml
    

負載平衡器會根據 WEIGHTED_ROUND_ROBIN 演算法和提供的自訂指標,將流量分配到端點。

設定雜湊環大小

如果服務必須盡可能減少快取失敗,請使用 RING_HASH 演算法。調整 minimumHashRingSize 欄位,即可在後端之間更精細地分配負載。雖然負載平衡器會自動管理環狀大小,但提供較高的最小值,有助於確保較大後端集的請求分配更平均。

apiVersion: networking.gke.io/v1
kind: GCPTrafficDistributionPolicy
metadata:
  name: ring-hash-policy
  namespace: default
spec:
  default:
    localityLbAlgorithm: RING_HASH
    # Defaults to 1024. Larger ring sizes result in more granular
    # load distributions. Supported range is 1 to 2048.
    minimumHashRingSize: 1024
  targetRefs:
  -   group: ""
    kind: Service
    name: my-cache-heavy-service

設定工作階段相依性

設定工作階段相依性,確保來自同一個用戶端的要求一律轉送至相同的後端 Pod。

使用 GCPTrafficDistributionPolicy 設定工作階段相依性 (預設)

本節所述的工作階段相依性類型,需要下列最低 GKE 版本:

  • CLIENT_IP、HEADER_FIELD、GENERATED_COOKIE 和 HTTP_COOKIE:1.35.2-gke.1269001 以上版本。
  • STRONG_COOKIE_AFFINITY:1.36.3-gke.1767000 以上版本。

GKE Gateway 支援所有工作階段相依性類型,方法是使用 GCPTrafficDistributionPolicy 資源。這項資源提供更精細的控制選項,例如根據自訂 HTTP 標頭或 Cookie 進行轉送。使用 GCPTrafficDistributionPolicy 設定工作階段相依性是預設且建議的方法。

下表說明使用 GCPTrafficDistributionPolicy 時支援的黏著類型:

相似度類型 說明
STRONG_COOKIE_AFFINITY 有狀態的 Cookie 型工作階段持續性。確保在擴充事件和 Pod 集區大小調整期間,工作階段黏著度仍能維持良好。您必須設定 cookie.name 欄位,並可視需要設定 cookie.path 和 cookie.ttl 欄位。適用於任何 localityLbAlgorithm 設定 (預設值為 ROUND_ROBIN)。
HTTP_COOKIE 根據 HTTP Cookie 建立關聯。回應第一個要求時,負載平衡器會產生 Cookie,並在 Set-Cookie 回應標頭中提供。在後續要求中,用戶端會傳回負載平衡器提供的 Cookie,而負載平衡器會使用該 Cookie,將要求一致地轉送至相同的 Pod。您必須設定 cookie.name 欄位,並可視需要設定 cookie.path 和 cookie.ttl 欄位。localityLbAlgorithm 欄位必須設為 MAGLEV 或 RING_HASH。
GENERATED_COOKIE 負載平衡器會產生 Cookie 來追蹤工作階段。全域外部應用程式負載平衡器的 Cookie 名稱為 GCLB,區域性內部應用程式負載平衡器和區域性外部應用程式負載平衡器的 Cookie 名稱則為 GCILB。Cookie 路徑為 /。您可以視需要設定 cookie.ttl 欄位,最長可達兩週;cookie.name 和 cookie.path 欄位不適用於這種類型。localityLbAlgorithm 欄位必須設為 MAGLEV 或 RING_HASH。
HEADER_FIELD 根據特定 HTTP 標頭的黏著度。localityLbAlgorithm 欄位必須設為 MAGLEV 或 RING_HASH。
CLIENT_IP 根據用戶端 IP 位址的相依性。localityLbAlgorithm 欄位必須設為 MAGLEV 或 RING_HASH。
NONE 停用工作階段相依性。

下列範例示範如何設定 GCPTrafficDistributionPolicy,並依相似度類別分組:以 Cookie 為基礎、以標頭為基礎,以及以用戶端 IP 為基礎的工作階段相似度。

如要將下列任一工作階段相依性設定套用至叢集,請按照下列步驟操作:

  1. 將所選資訊清單儲存為 policy.yaml。
  2. 將資訊清單套用至叢集:

    kubectl apply -f policy.yaml
    

Cookie 型工作階段相依性包括 STRONG_COOKIE_AFFINITY、HTTP_COOKIE 和 GENERATED_COOKIE 相依性類型。

有狀態 Cookie 黏性 (STRONG_COOKIE_AFFINITY)

有狀態 Cookie 親和性 (STRONG_COOKIE_AFFINITY) 提供有狀態工作階段持續性,即使在後端擴充事件期間也能維持黏性。

apiVersion: networking.gke.io/v1
kind: GCPTrafficDistributionPolicy
metadata:
  name: strong-cookie-affinity-policy
  namespace: default
spec:
  default:
    sessionAffinity:
      type: STRONG_COOKIE_AFFINITY
      cookie:
        name: "GKE_STATEFUL_SESSION"
        path: "/"
        ttl: "24h"
  targetRefs:
  - group: ""
    kind: Service
    name: my-stateful-service

HTTP Cookie 親和性 (HTTP_COOKIE)

HTTP_COOKIE 相似類型會根據 Set-Cookie 標頭中傳回的特定命名 Cookie 建立相似度。如要使用 NONE 和 STRONG_COOKIE_AFFINITY 以外的工作階段相依性類型,您必須將 localityLbAlgorithm 欄位設為 MAGLEV 或 RING_HASH。

apiVersion: networking.gke.io/v1
kind: GCPTrafficDistributionPolicy
metadata:
  name: http-cookie-affinity-policy
  namespace: default
spec:
  default:
    sessionAffinity:
      type: HTTP_COOKIE
      cookie:
        name: "my-app-session-id"
        path: "/"
        ttl: "3600s"
    # HTTP_COOKIE affinity requires localityLbAlgorithm to be MAGLEV or RING_HASH.
    localityLbAlgorithm: MAGLEV
  targetRefs:
  - group: ""
    kind: Service
    name: my-stateful-service

已產生 Cookie 的相依性 (GENERATED_COOKIE)

GENERATED_COOKIE 相依性類型可讓負載平衡器自動產生工作階段 Cookie 並命名。您可以視需要設定 cookie.ttl 欄位的值,最長可達兩週 (336h)。

apiVersion: networking.gke.io/v1
kind: GCPTrafficDistributionPolicy
metadata:
  name: generated-cookie-affinity-policy
  namespace: default
spec:
  default:
    sessionAffinity:
      type: GENERATED_COOKIE
      cookie:
        ttl: "2h30m"
    # GENERATED_COOKIE affinity requires localityLbAlgorithm to be MAGLEV or RING_HASH.
    localityLbAlgorithm: MAGLEV
  targetRefs:
  - group: ""
    kind: Service
    name: my-stateful-service

Cookie 工作階段相依性 TTL 為零時,行為如下:

  • 所有以 Cookie 為基礎的工作階段相依性 (STRONG_COOKIE_AFFINITY、HTTP_COOKIE 和 GENERATED_COOKIE) 都具有 ttl 屬性。

  • 如果存留時間為零秒,表示負載平衡器不會為 Cookie 指派 Expires 屬性。在這種情況下,用戶端會將 Cookie 視為工作階段 Cookie。工作階段的定義因用戶端而異:

    • 部分用戶端 (例如網路瀏覽器) 會在整個瀏覽工作階段中保留 Cookie。這種做法代表 Cookie 會在多個要求中持續存在,直到應用程式關閉為止。
    • 其他用戶端會將工作階段視為單一 HTTP 要求,並在工作階段結束後立即捨棄 Cookie。

標頭式工作階段相依性

HEADER_FIELD 親和性類型會根據特定 HTTP 標頭轉送流量,適用於 A/B 測試或不適合使用 Cookie 的特殊用戶端轉送等情境。如要使用 NONE 和 STRONG_COOKIE_AFFINITY 以外的工作階段相依性類型,您必須將 localityLbAlgorithm 欄位設為 MAGLEV 或 RING_HASH。與預設的 ROUND_ROBIN 不同,這些演算法支援以自訂欄位 (例如 HTTP 標頭) 為基礎的一致性雜湊。

apiVersion: networking.gke.io/v1
kind: GCPTrafficDistributionPolicy
metadata:
  name: header-affinity-policy
  namespace: default
spec:
  default:
    sessionAffinity:
      type: HEADER_FIELD
      httpHeaderName: "X-User-Group-ID"
    localityLbAlgorithm: MAGLEV
  targetRefs:
  - group: ""
    kind: Service
    name: SERVICE_NAME

以用戶端 IP 位址為基礎的工作階段相依性

CLIENT_IP 相依性類型會盡可能將來自特定用戶端 IP 位址的流量轉送至同一個後端 Pod。如要使用 NONE 和 STRONG_COOKIE_AFFINITY 以外的工作階段相依性類型,您必須將 localityLbAlgorithm 欄位設為 MAGLEV 或 RING_HASH。

apiVersion: networking.gke.io/v1
kind: GCPTrafficDistributionPolicy
metadata:
  name: client-ip-affinity-policy
  namespace: default
spec:
  default:
    sessionAffinity:
      type: CLIENT_IP
    localityLbAlgorithm: MAGLEV
  targetRefs:
  - group: ""
    kind: Service
    name: SERVICE_NAME

驗證政策

為確保 GCPTrafficDistributionPolicy 設定正確且有效,請在套用後驗證其狀態:

  1. 執行下列指令,檢查政策狀態:

    kubectl describe gcptrafficdistributionpolicy POLICY_NAME
    

    將 POLICY_NAME 替換為政策名稱。

  2. 在輸出內容中,查看 Conditions 區段。如果狀態為 True,原因為 Attached,表示設定有效且已啟用。

使用 GCPBackendPolicy 設定工作階段相依性

本節說明如何使用 GCPBackendPolicy 設定工作階段相依性。

您可以根據下列條件設定 GCPBackendPolicy 工作階段相依性:

  • 用戶端 IP 位址 (CLIENT_IP)
  • 產生的 Cookie (GENERATED_COOKIE)

使用 GCPBackendPolicy 為 Service 設定工作階段相依性時,閘道會將後端服務的 localityLbPolicy 設定設為 MAGLEV。從 GCPBackendPolicy 移除工作階段相依性時,閘道會將 localityLbPolicy 設定還原為預設值 ROUND_ROBIN。

下列 GCPBackendPolicy 資訊清單會根據用戶端 IP 位址指定工作階段相依性:

服務

apiVersion: networking.gke.io/v1
kind: GCPBackendPolicy
metadata:
  name: my-backend-policy
  namespace: lb-service-namespace
spec:
  default:
    # On a best-effort basis, send requests from a specific client IP address
    # to the same backend. This field also sets the load balancer locality
    # policy to MAGLEV. For more information, see
    # https://docs.cloud.google.com/load-balancing/docs/backend-service#lb-locality-policy
    sessionAffinity:
      type: CLIENT_IP
  targetRef:
    group: ""
    kind: Service
    name: lb-service

多叢集服務

apiVersion: networking.gke.io/v1
kind: GCPBackendPolicy
metadata:
  name: my-backend-policy
  namespace: lb-service-namespace
spec:
  default:
    # On a best-effort basis, send requests from a specific client IP address
    # to the same backend. This field also sets the load balancer locality
    # policy to MAGLEV. For more information, see
    # https://docs.cloud.google.com/load-balancing/docs/backend-service#lb-locality-policy
    sessionAffinity:
      type: CLIENT_IP
  targetRef:
    group: net.gke.io
    kind: ServiceImport
    name: lb-service

下列 GCPBackendPolicy 資訊清單會根據產生的 Cookie 指定工作階段相依性,並將 Cookie 存留時間設為 50 秒:

服務

apiVersion: networking.gke.io/v1
kind: GCPBackendPolicy
metadata:
  name: my-backend-policy
  namespace: lb-service-namespace
spec:
  default:
    # Include an HTTP cookie in the Set-Cookie header of the response.
    # This field also sets the load balancer locality policy to MAGLEV. For more
    # information, see
    # https://docs.cloud.google.com/load-balancing/docs/l7-internal#generated_cookie_affinity.
    sessionAffinity:
      type: GENERATED_COOKIE
      cookieTtlSec: 50  # The cookie expires in 50 seconds.
  targetRef:
    group: ""
    kind: Service
    name: lb-service

多叢集服務

apiVersion: networking.gke.io/v1
kind: GCPBackendPolicy
metadata:
  name: my-backend-policy
  namespace: lb-service-namespace
spec:
  default:
    # Include an HTTP cookie in the Set-Cookie header of the response.
    # This field also sets the load balancer locality policy to MAGLEV. For more
    # information, see
    # https://docs.cloud.google.com/load-balancing/docs/l7-internal#generated_cookie_affinity.
    sessionAffinity:
      type: GENERATED_COOKIE
      cookieTtlSec: 50  # The cookie expires in 50 seconds.
  targetRef:
    group: net.gke.io
    kind: ServiceImport
    name: lb-service

設定連線排除逾時

本節說明的功能適用於搭載 1.24 以上版本的 GKE 叢集。

您可以使用 GCPBackendPolicy 設定連線排除逾時。連線排除逾時時間是指等待連線排除的時間 (以秒為單位)。逾時時間長度可介於 0 到 3600 秒之間。預設值為 0,也會停用連線排除功能。

下列 GCPBackendPolicy 資訊清單指定連線排除逾時時間為 60 秒:

服務

apiVersion: networking.gke.io/v1
kind: GCPBackendPolicy
metadata:
  name: my-backend-policy
  namespace: lb-service-namespace
spec:
  default:
    connectionDraining:
      drainingTimeoutSec: 60
  targetRef:
    group: ""
    kind: Service
    name: lb-service

多叢集服務

apiVersion: networking.gke.io/v1
kind: GCPBackendPolicy
metadata:
  name: my-backend-policy
  namespace: lb-service-namespace
spec:
  default:
    connectionDraining:
      drainingTimeoutSec: 60
  targetRef:
    group: net.gke.io
    kind: ServiceImport
    name: lb-service

InferencePool

apiVersion: networking.gke.io/v1
kind: GCPBackendPolicy
metadata:
  name: my-backend-policy
  namespace: lb-service-namespace
spec:
  default:
    connectionDraining:
      drainingTimeoutSec: 60
  # Attach to an InferencePool in the cluster.
  targetRef:
    group: inference.networking.k8s.io
    kind: InferencePool
    name: my-inference-pool

多叢集 InferencePool

yaml apiVersion: networking.gke.io/v1 kind: GCPBackendPolicy metadata: name: my-backend-policy namespace: lb-service-namespace spec: default: connectionDraining: drainingTimeoutSec: 60 # Attach to a multi-cluster InferencePool. targetRef: group: networking.gke.io kind: GCPInferencePoolImport name: my-inference-pool-import

在指定的逾時時間內,GKE 會等待已移除後端的現有要求完成。負載平衡器不會將新要求傳送至已移除的後端。達到逾時時間長度後,GKE 會關閉與後端的所有剩餘連線。

HTTP 存取記錄

本節說明的功能適用於搭載 1.24 以上版本的 GKE 叢集。

根據預設:

  • 閘道控制器會將用戶端的所有 HTTP 要求記錄到 Cloud Logging。
  • 取樣率為 1,000,000,代表所有要求都會記錄。
  • 未記錄任何選填欄位。

您可以使用 GCPBackendPolicy,透過下列三種方式停用閘道的存取記錄:

  • 您可以保留 GCPBackendPolicy,不含 logging 區段
  • 您可以將 logging.enabled 設為 false
  • 您可以將 logging.enabled 設為 true,並將 logging.sampleRate 設為 0

您也可以設定存取記錄取樣率和選填欄位清單,例如 tls.cipher 或 orcaLoadReport。

如要啟用選填欄位的記錄功能,請按照下列步驟操作:

  • 將 logging.OptionalMode 設為 CUSTOM。
  • 提供要記錄在 logging.optionalFields 中的選填欄位清單。如需支援的欄位清單,請參閱「記錄和監控」。

您可以透過下列兩種方式,停用選項欄位的記錄功能:

  • 您可以移除 logging.optionalFields 的所有項目。
  • 您可以將 logging.OptionalMode 設為 EXCLUDE_ALL_OPTIONAL。

下列 GCPBackendPolicy 資訊清單會修改存取記錄的預設取樣率,並將其設為 HTTP 要求的 50%。資訊清單也可為特定 Service 資源啟用兩個選用欄位的記錄功能:

服務

apiVersion: networking.gke.io/v1
kind: GCPBackendPolicy
metadata:
  name: my-backend-policy
  namespace: lb-service-namespace
spec:
  default:
    # Access logging configuration for the load balancer.
    logging:
      enabled: true
      # Log 50% of the requests. The value must be an integer between 0 and
      # 1000000. To get the proportion of requests to log, GKE
      # divides this value by 1000000.
      sampleRate: 500000
      # Log specific optional fields.
      optionalMode: CUSTOM
      optionalFields:
      - tls.cipher
      - orcaLoadReport.cpu_utilization
  targetRef:
    group: ""
    kind: Service
    name: lb-service

多叢集服務

apiVersion: networking.gke.io/v1
kind: GCPBackendPolicy
metadata:
  name: my-backend-policy
  namespace: lb-service-namespace
spec:
  default:
    # Access logging configuration for the load balancer.
    logging:
      enabled: true
      # Log 50% of the requests. The value must be an integer between 0 and
      # 1000000. To get the proportion of requests to log, GKE
      # divides this value by 1000000.
      sampleRate: 500000
      # Log specific optional fields.
      optionalMode: CUSTOM
      optionalFields:
      - tls.cipher
      - orcaLoadReport.cpu_utilization
  targetRef:
    group: net.gke.io
    kind: ServiceImport
    name: lb-service

InferencePool

apiVersion: networking.gke.io/v1
kind: GCPBackendPolicy
metadata:
  name: my-backend-policy
  namespace: lb-service-namespace
spec:
  default:
    # Access logging configuration for the load balancer.
    logging:
      enabled: true
      # Log 50% of the requests. The value must be an integer between 0 and
      # 1000000. To get the proportion of requests to log, GKE
      # divides this value by 1000000.
      sampleRate: 500000
      # Log specific optional fields.
      optionalMode: CUSTOM
      optionalFields:
      - tls.cipher
      - orcaLoadReport.cpu_utilization
  # Attach to an InferencePool in the cluster.
  targetRef:
    group: inference.networking.k8s.io
    kind: InferencePool
    name: my-inference-pool

多叢集 InferencePool

apiVersion: networking.gke.io/v1
kind: GCPBackendPolicy
metadata:
  name: my-backend-policy
  namespace: lb-service-namespace
spec:
  default:
    # Access logging configuration for the load balancer.
    logging:
      enabled: true
      # Log 50% of the requests. The value must be an integer between 0 and
      # 1000000. To get the proportion of requests to log, GKE
      # divides this value by 1000000.
      sampleRate: 500000
      # Log specific optional fields.
      optionalMode: CUSTOM
      optionalFields:
      - tls.cipher
      - orcaLoadReport.cpu_utilization
  # Attach to a multi-cluster InferencePool.
  targetRef:
    group: networking.gke.io
    kind: GCPInferencePoolImport
    name: my-inference-pool-import

這個資訊清單包含下列欄位:

  • enable: true:明確啟用存取記錄。記錄檔會顯示在 Logging 中。
  • sampleRate: 500000:指定記錄 50% 的封包。您可以使用的值介於 0 到 1,000,000 之間。GKE 會將這個值除以 1, 000,000,轉換為介於 [0,1] 範圍內的浮點值。只有在 enable 設為 true 時,這個欄位才適用。sampleRate 是選用欄位,但如果設定了這個欄位,也必須設定 enable: true。如果 enable 設為 true,且未提供 sampleRate,GKE 會將 enable 設為 false。
  • optionalMode: CUSTOM:指定記錄項目應包含一組 optionalFields。
  • optionalFields: tls.cipher, orcaLoadReport.cpu_utilization:指定記錄項目應包含用於 TLS 握手的加密編譯名稱,以及服務的 CPU 使用率 (如有)。僅在 spec.protocol 欄位為 HTTP 時支援。

為單一叢集閘道設定流量型自動調度資源功能

確認 GKE 叢集執行的是 1.31.1-gke.2008000 以上版本。

如要在單一叢集閘道中,啟用依流量自動調度資源和依容量負載平衡的功能,您可以設定 Service 容量。Service 容量是指在 Pod 自動調度資源或流量溢位至其他可用叢集之前,Service 可接收的流量容量。

如要設定服務容量,請建立服務和相關聯的 GCPBackendPolicy。GCPBackendPolicy 資訊清單會使用 maxRatePerEndpoint 欄位,定義 Service 中每個 Pod 的每秒要求數 (RPS) 上限值。下列 GCPBackendPolicy 資訊清單定義的每秒要求數上限為 10:

apiVersion: networking.gke.io/v1
kind: GCPBackendPolicy
metadata:
  name: store
spec:
  default:
    maxRatePerEndpoint: 10
  targetRef:
    group: ""
    kind: Service
    name: store

如要進一步瞭解如何依據流量自動調度資源,請參閱「依據負載平衡器流量自動調度資源」。

疑難排解

本節提供疑難排解指南,說明使用政策設定閘道資源時的常見問題。

GCPTrafficDistributionPolicy 未生效

症狀:流量未按照政策中定義的工作階段相依性或位置設定分配。

原因:這通常是因為政策未正確繫結至 Service,或 Gateway 控制器嘗試將設定同步至負載平衡器時發生驗證錯誤。

解決方法:

  1. 驗證政策審查狀態:確認政策是否已附加至服務:

    kubectl describe gcptrafficdistributionpolicy POLICY_NAME
    

    將 POLICY_NAME 替換為政策名稱。

    在輸出內容中,尋找 Conditions 區段。如果狀態為 True,原因為 Attached,表示設定有效且已套用。如果狀態為 False,請檢查 Reason 和 Message 欄位是否有驗證錯誤 (例如所選親和性類型不支援演算法)。

  2. 確認閘道設定同步:確認管理流量的閘道已成功將這些設定與雲端基礎架構同步。

    在「Status」部分,確認 Programmed 條件的 Status 為 True。如果狀態為 False,表示閘道控制器發生錯誤,可能與 GCPTrafficDistributionPolicy 有關。

    請查看 Programmed 條件旁的 Reason 和 Message 欄位,立即瞭解詳情。如要查看更精細的錯誤訊息或同步失敗記錄,請查看輸出內容底部的 Events。

多個 GCPBackendPolicy 附加至同一個 Service

症狀:

將 GCPBackendPolicy 附加至 Service 或 ServiceImport 時,可能會出現下列狀態條件:

status:
  conditions:
    - lastTransitionTime: "2023-09-26T20:18:03Z"
      message: conflicted with GCPBackendPolicy "[POLICY_NAME]" of higher precedence, hence not applied
      reason: Conflicted
      status: "False"
      type: Attached

原因:

這個狀態條件表示您嘗試將第二個 GCPBackendPolicy 套用至已附加 GCPBackendPolicy 的 Service 或 ServiceImport。

GKE Gateway 不支援將多個 GCPBackendPolicy 附加至同一個 Service 或 ServiceImport。詳情請參閱「限制和限制」。

解決方法:

設定單一 GCPBackendPolicy,納入所有自訂設定,並附加至目標資源 (Service、ServiceImport、InferencePool 或 GCPInferencePoolImport)。

流量拆分期間忽略工作階段相依性

症狀:

即使已設定工作階段相依性,要求仍不會一律轉送至相同的後端 Pod。

原因:

加權流量拆分優先於工作階段相依性。如果 HTTPRoute 為多個後端定義權重,負載平衡器會先根據權重選取後端,再套用相似度邏輯。

解決方法:

如果 HTTPRoute 規則需要工作階段黏性,請避免在該規則使用加權流量拆分。

找不到 Cloud Armor 安全性政策

症狀:

在區域性閘道啟用 Cloud Armor 時,可能會出現下列錯誤訊息:

Invalid value for field 'resource': '{
"securityPolicy":"projects/123456789/regions/us-central1/securityPolicies/<policy_name>"}'.
The given security policy does not exist.

原因:

錯誤訊息指出 Google Cloud 專案中沒有指定的區域性 Cloud Armor 安全性政策。

解決方法:

在專案中建立區域性 Cloud Armor 安全性政策,並在 GCPBackendPolicy 中參照這項政策。

後續步驟