設定區域性外部應用程式負載平衡器的流量管理

本文將舉例說明如何運用流量管理功能處理特定用途。還能用於許多其他用途。

本文件包含下列負載平衡器的範例:

  • 區域性外部應用程式負載平衡器
  • 區域性內部應用程式負載平衡器
  • 跨區域內部應用程式負載平衡器

區域性外部應用程式負載平衡器與區域性內部應用程式負載平衡器。如要瞭解地區負載平衡器的流量管理設定,請參閱地區網址對應 API 地區後端服務 API 說明文件,當中列出所有欄位,包括關係、限制和基數的語意。

這兩種負載平衡器唯一的差異在於負載平衡架構,如下所示:

  • 區域性外部應用程式負載平衡器使用 EXTERNAL_MANAGED
  • 區域性內部應用程式負載平衡器使用 INTERNAL_MANAGED

區域性內部應用程式負載平衡器與跨區域內部應用程式負載平衡器。流量管理設定:

除了本頁面說明的進階轉送功能之外,支援的應用程式負載平衡器也與服務擴充功能整合,可讓您將自訂邏輯插入負載平衡資料路徑。

事前準備

請務必瞭解流量管理機制。詳情請參閱「區域性外部應用程式負載平衡器的流量管理總覽」。

設定流量管理

在所選設定環境中,您可以使用 YAML 設定檔設定流量管理。網址對應和後端服務各有專屬的 YAML 檔案。視所需功能而定,您需要編寫網址對應 YAML 檔案、後端服務 YAML 檔案,或兩者皆是。

如需編寫這些 YAML 檔案的協助,請參閱本頁面的範例和 Cloud Load Balancing API 說明文件。

系統不支援 Google Cloud 控制台。

如為區域內部應用程式負載平衡器和區域外部應用程式負載平衡器,請參閱區域網址對應 API 區域後端服務 API 說明文件,瞭解完整欄位清單,包括關係、限制和基數的語意。

將流量對應至單一服務

將所有流量傳送至單一服務。請務必替換預留位置。

    defaultService: projects/PROJECT_ID/regions/REGION/backendServices/BACKEND_SERVICE_1
    hostRules:
    - hosts:
      - '*'
      pathMatcher: matcher1
    name: URL_MAP_NAME
    pathMatchers:
    - defaultService: projects/PROJECT_ID/regions/REGION/backendServices/BACKEND_SERVICE_1
      name: matcher1
      routeRules:
        - matchRules:
            - prefixMatch: /PREFIX
          priority: 1
          routeAction:
            weightedBackendServices:
              - backendService: projects/PROJECT_ID/regions/REGION/backendServices/BACKEND_SERVICE_1
                weight: 100

利用流量拆分技巧,將流量導向兩項服務

將流量拆分給兩項或多項服務。請務必替換預留位置。

   defaultService: projects/PROJECT_ID/regions/REGION/backendServices/BACKEND_SERVICE_1
   hostRules:
   - hosts:
     - '*'
     pathMatcher: matcher1
   name: URL_MAP_NAME
   pathMatchers:
   - defaultService: projects/PROJECT_ID/regions/REGION/backendServices/BACKEND_SERVICE_1
     name: matcher1
     routeRules:
     - matchRules:
       - prefixMatch: /PREFIX
       priority: 2
       routeAction:
         weightedBackendServices:
         - backendService: projects/PROJECT_ID/regions/REGION/backendServices/BACKEND_SERVICE_1
           weight: 95
         - backendService: projects/PROJECT_ID/regions/REGION/backendServices/BACKEND_SERVICE_2
           weight: 5

設定網址重新導向

下列範例會傳回可設定的 3xx 回應碼。這個範例也會使用適當的 URI 來設定 Location 回應標頭,以取代重新導向動作中所指定的主機和路徑。

   defaultService: projects/PROJECT_ID/regions/REGION/backendServices/BACKEND_SERVICE_1
   name: URL_MAP_NAME
   hostRules:
   - hosts:
     - "HOST TO REDIRECT FROM" # Use * for all hosts
     pathMatcher: matcher1
   pathMatchers:
   - defaultService: projects/PROJECT_ID/regions/REGION/backendServices/BACKEND_SERVICE_1
     name: matcher1
     defaultUrlRedirect:
       hostRedirect: "HOST TO REDIRECT TO" # Omit to keep the requested host
       pathRedirect: "PATH TO REDIRECT TO" # Omit to keep the requested path
       redirectResponseCode: MOVED_PERMANENTLY_DEFAULT
       stripQuery: True

建立流量鏡射

除了將要求轉送到所選的後端服務外,您也可以射後不理的模式,將完全相同的要求傳送至設定的鏡射後端服務。也就是說,負載平衡器不會等待後端回應,而是直接傳送鏡像要求。要求鏡射很適合用來測試新版本的後端服務。您也可以使用這項功能,針對後端服務的偵錯版本 (而不是正式版本) 偵錯實際工作環境的錯誤。

根據預設,鏡像後端服務會收到所有要求,即使原始流量是分配給多個加權後端服務也一樣。您可以設定鏡像後端服務,只接收一定比例的要求。方法是使用選用的 mirrorPercent 旗標,指定要鏡像處理的要求百分比,並以介於 0 和 100.0 之間的值表示。

   defaultService: projects/PROJECT_ID/regions/REGION/backendServices/BACKEND_SERVICE_1
   name: regional-lb-map
   region: region/REGION
   hostRules:
   - hosts:
     - '*'
     pathMatcher: matcher1
   pathMatchers:
   - defaultService: projects/PROJECT_ID/regions/REGION/backendServices/BACKEND_SERVICE_1
     name: matcher1
     routeRules:
       - matchRules:
           - prefixMatch: /PREFIX
         priority: 1
         routeAction:
           weightedBackendServices:
             - backendService: projects/PROJECT_ID/regions/REGION/backendServices/BACKEND_SERVICE_1
               weight: 100
           requestMirrorPolicy:
             backendService: projects/PROJECT_ID/regions/REGION/backendServices/BACKEND_SERVICE_2
             mirrorPercent: 50.0

使用流量鏡像時,請注意下列限制:

  • 如果兩個後端服務都具有代管執行個體群組、區域性 NEG 或混合式 NEG 後端,則支援流量鏡射。不支援網際網路 NEG、無伺服器 NEG 和 Private Service Connect 後端。
  • 對鏡像後端服務提出的要求不會產生任何 Cloud Logging 和 Cloud Monitoring 的記錄或指標。

重新編寫要求的網址

重新編寫網址的主機名稱部分、網址的路徑部分或兩者均重新編寫,然後再傳送要求至選取的後端服務。請務必替換預留位置。

   defaultService: projects/PROJECT_ID/regions/REGION/backendServices/BACKEND_SERVICE_1
   name: regional-lb-map
   region: region/REGION
   hostRules:
   - hosts:
     - '*'
     pathMatcher: matcher1
   pathMatchers:
   - defaultService: projects/PROJECT_ID/regions/REGION/backendServices/BACKEND_SERVICE_1
     name: matcher1
     routeRules:
       - matchRules:
           - prefixMatch: /PREFIX
         priority: PRIORITY # 0 is highest
         routeAction:
           weightedBackendServices:
             - backendService: projects/PROJECT_ID/regions/REGION/backendServices/BACKEND_SERVICE_1
               weight: 100
           urlRewrite:
             hostRewrite: "new-host-name.com" # Omit to keep the requested host
             pathPrefixRewrite: "/new-path/" # Omit to keep the requested path

重試要求

設定負載平衡器重試失敗要求的條件、負載平衡器在重試前等待的時間,以及允許的重試次數上限。

   defaultService: projects/PROJECT_ID/regions/REGION/backendServices/BACKEND_SERVICE_1
   name: regional-lb-map
   region: region/REGION
   hostRules:
   - hosts:
     - '*'
     pathMatcher: matcher1
   pathMatchers:
   - defaultService: projects/PROJECT_ID/regions/REGION/backendServices/BACKEND_SERVICE_1
     name: matcher1
     routeRules:
       - matchRules:
           - prefixMatch: /PREFIX
         priority: PRIORITY # 0 is highest
         routeAction:
           weightedBackendServices:
             - backendService: projects/PROJECT_ID/regions/REGION/backendServices/BACKEND_SERVICE_1
               weight: 100
           retryPolicy:
             retryConditions: 502, 504
             numRetries: 3
             perTryTimeout:
               seconds: 1
               nanos: 500000000

指定路徑逾時

為所選路徑指定逾時時間。逾時時間的計算方式為從要求完全處理完畢到回應完全處理完畢。逾時 包括所有重試。請務必替換預留位置。

   defaultService: projects/PROJECT_ID/regions/REGION/backendServices/BACKEND_SERVICE_1
   name: regional-lb-map
   region: region/REGION
   hostRules:
   - hosts:
     - '*'
     pathMatcher: matcher1
   pathMatchers:
   - defaultService: projects/PROJECT_ID/regions/REGION/backendServices/BACKEND_SERVICE_1
     name: matcher1
     routeRules:
       - matchRules:
           - prefixMatch: /PREFIX
         priority: PRIORITY # 0 is highest
         routeAction:
           weightedBackendServices:
             - backendService: projects/PROJECT_ID/regions/REGION/backendServices/BACKEND_SERVICE_1
               weight: 100
           timeout:
             seconds: 30
             nanos: 500000000

設定錯誤植入

處理模擬故障的要求時,產生高延遲、服務超載、服務故障和網路分區等錯誤。這項功能可用於測試服務對模擬故障的彈性。

   defaultService: projects/PROJECT_ID/regions/REGION/backendServices/BACKEND_SERVICE_1
   name: regional-lb-map
   region: region/REGION
   hostRules:
   - hosts:
     - '*'
     pathMatcher: matcher1
   pathMatchers:
   - defaultService: projects/PROJECT_ID/regions/REGION/backendServices/BACKEND_SERVICE_1
     name: matcher1
     routeRules:
       - matchRules:
           - prefixMatch: /PREFIX
         priority: PRIORITY # 0 is highest
         routeAction:
           weightedBackendServices:
             - backendService: projects/PROJECT_ID/regions/REGION/backendServices/BACKEND_SERVICE_1
               weight: 100
           faultInjectionPolicy:
             delay:
               fixedDelay:
                 seconds: 10
                 nanos: 500000000
               percentage: 25
             abort:
               httpStatus: 503
               percentage: 50

設定 CORS

設定跨源資源共享 (CORS) 政策,處理用於強制執行 CORS 要求的設定。

   defaultService: projects/PROJECT_ID/regions/REGION/backendServices/BACKEND_SERVICE_1
   name: regional-lb-map
   region: region/REGION
   hostRules:
   - hosts:
     - '*'
     pathMatcher: matcher1
   pathMatchers:
   - defaultService: projects/PROJECT_ID/regions/REGION/backendServices/BACKEND_SERVICE_1
     name: matcher1
     routeRules:
       - matchRules:
           - prefixMatch: /PREFIX
         priority: PRIORITY # 0 is highest
         routeAction:
           weightedBackendServices:
             - backendService: projects/PROJECT_ID/regions/REGION/backendServices/BACKEND_SERVICE_1
               weight: 100
           corsPolicy:
               allowOrigins: my-domain.com
               allowMethods: GET, POST
               allowHeaders: Authorization, Content-Type
               maxAge: 1200
               allowCredentials: True

新增及移除要求和回應標頭

在將要求傳送至後端服務之前,新增及移除要求標頭。從後端服務收到回應後,這項設定也可以新增或刪除回應標頭。

區域性外部應用程式負載平衡器和內部應用程式負載平衡器也支援在自訂標頭中使用變數。您可以在自訂標頭值 (headerValue) 欄位中指定一或多個變數,這些變數隨後會轉換為對應的每個要求值。如需支援的標頭值清單,請參閱「在網址對應中建立自訂標頭」。

   defaultService: projects/PROJECT_ID/regions/REGION/backendServices/BACKEND_SERVICE_1
   name: regional-lb-map
   region: region/REGION
   hostRules:
   - hosts:
     - '*'
     pathMatcher: matcher1
   pathMatchers:
   - defaultService: projects/PROJECT_ID/regions/REGION/backendServices/BACKEND_SERVICE_1
     name: matcher1
     routeRules:
       - matchRules:
           - prefixMatch: /PREFIX
         priority: PRIORITY # 0 is highest
         routeAction:
           weightedBackendServices:
             - backendService: projects/PROJECT_ID/regions/REGION/backendServices/BACKEND_SERVICE_1
               weight: 100
               headerAction:
                 requestHeadersToAdd:
                 - headerName: header-1-name
                   headerValue: header-1-value
                   replace: True
                 requestHeadersToRemove:
                 - header-2-name
                 - header-3-name
                 responseHeadersToAdd:
                 - headerName: header-4-name
                   headerValue: header-4-value
                   replace: True
                responseHeadersToRemove:
                - header-5-name
                - header-6-name

設定離群值偵測

指定移除 NEG 中健康狀態不良的後端 VM 或端點的條件,也會定義條件,決定後端或端點何時會被視為健康狀態良好到足以再次接收流量。請務必替換預留位置。

    loadBalancingScheme: LOAD_BALANCING_SCHEME
    localityLbPolicy: RANDOM
    name: projects/PROJECT_ID/regions/REGION/backendServices/BACKEND_SERVICE_1
    outlierDetection:
      baseEjectionTime:
        nanos: 0
        seconds: '30'
      consecutiveErrors: 5
      consecutiveGatewayFailure: 3
      enforcingConsecutiveErrors: 2
      enforcingConsecutiveGatewayFailure: 100
      enforcingSuccessRate: 100
      interval:
        nanos: 0
        seconds: '1'
      maxEjectionPercent: 50
      successRateMinimumHosts: 5
      successRateRequestVolume: 100
      successRateStdevFactor: 1900
    region: region/REGION

設定斷路機制

您可以透過斷路設定失敗門檻,避免用戶端要求造成後端過載。要求達到您設定的上限後,負載平衡器就會停止允許新連線或傳送額外要求,讓後端有時間復原。因此,斷路機制會向用戶端傳回錯誤,而不是讓後端過載,藉此避免連鎖性故障。這樣一來,系統就能在提供時間管理過載情況的同時,放送部分流量,例如透過自動調度資源增加容量,處理流量尖峰。

設定每個連線的要求數量上限,以及後端服務的連線量上限。同時限制待處理要求和重試次數。

    loadBalancingScheme: LOAD_BALANCING_SCHEME # EXTERNAL_MANAGED or INTERNAL_MANAGED
    localityLbPolicy: RANDOM
    affinityCookieTtlSec: 0
    backends:
    - balancingMode: UTILIZATION
      capacityScaler: 1.0
      group: region/REGION/instanceGroups/INSTANCE_GROUP
      maxUtilization: 0.8
    circuitBreakers:
      maxConnections: 1000
      maxPendingRequests: 200
      maxRequests: 1000
      maxRequestsPerConnection: 100
      maxRetries: 3
    connectionDraining:
      drainingTimeoutSec: 0
    healthChecks:
    - region/REGION/healthChecks/HEALTH_CHECK

設定流量拆分:詳細步驟

本範例將示範以下步驟:

  1. 針對不同的服務建立獨特的範本。

  2. 為這些範本建立執行個體群組。

  3. 建立設定 95% / 5% 流量分配的轉送規則。

  4. 發送 curl 指令,顯示流量拆分百分比大致與設定相符。

此處的操作說明假設情況如下:

  • 地區為 us-west1
  • 已建立目標 Proxy 和轉送規則,以及名為 regional-lb-map 的網址對應。

  • 網址對應會將所有流量傳送到名為 red-service 的預設後端服務。

  • 您設定的替代路徑會分別將 5% 和 95% 的流量傳送至 blue-servicegreen-service

  • 使用路徑比對器。

  • 您正在使用 Cloud Shell 或是已安裝 bash 的其他環境。

定義服務

下列 bash 函式會建立後端服務,包括執行個體範本和代管執行個體群組。

此處的操作說明假設您已建立 HTTP 健康狀態檢查 (regional-lb-basic-check)。如需操作說明,請參閱「設定區域性外部應用程式負載平衡器」。
function make_service() {
  local name="$1"
  local region="$2"
  local zone="$3"
  local network="$4"
  local subnet="$5"
  local subdir="$6"

  www_dir="/var/www/html/$subdir"

  (set -x; \
  gcloud compute instance-templates create "${name}-template" \
    --region="$region" \
    --network="$network" \
    --subnet="$subnet" \
    --tags=allow-ssh,load-balanced-backend \
    --image-family=debian-12 \
    --image-project=debian-cloud \
    --metadata=startup-script="#! /bin/bash
  apt-get update
  apt-get install apache2 -y
  a2ensite default-ssl
  a2enmod ssl
  sudo mkdir -p $www_dir
  /bin/hostname | sudo tee ${www_dir}index.html
  systemctl restart apache2"; \
  gcloud compute instance-groups managed create \
    "${name}-instance-group" \
    --zone="$zone" \
    --size=2 \
    --template="${name}-template"; \
  gcloud compute backend-services create "${name}-service" \
    --load-balancing-scheme=LOAD_BALANCING_SCHEME\
    --protocol=HTTP \
    --health-checks=regional-lb-basic-check \
    --health-checks-region="$region" \
    --region="$region"; \
  gcloud compute backend-services add-backend "${name}-service" \
    --balancing-mode='UTILIZATION' \
    --instance-group="${name}-instance-group" \
    --instance-group-zone="$zone" \
    --region="$region")
}

建立服務

呼叫函式來提供 redgreenblue 三項服務。red 服務是 / 要求的預設服務。greenblue 服務都會在 /PREFIX 進行設定,使其可分別處理 95% 和 5% 的流量。

make_service red us-west1 us-west1-a lb-network backend-subnet ""
make_service green us-west1 us-west1-a lb-network backend-subnet /PREFIX
make_service blue us-west1 us-west1-a lb-network backend-subnet /PREFIX

建立網址對應

gcloud

  1. 使用 gcloud compute url-maps export 指令匯出現有網址對應:

    gcloud compute url-maps export regional-lb-map \
      --destination=regional-lb-map-config.yaml \
      --region=us-west1
    
  2. 在網址對應檔案 regional-lb-map-config.yaml 結尾新增下列內容,即可更新檔案:

    hostRules:
    - hosts:
      - '*'
      pathMatcher: matcher1
    pathMatchers:
    - defaultService: projects/PROJECT_ID/regions/us-west1/backendServices/red-service
      name: matcher1
      routeRules:
      - priority: 2
        matchRules:
          - prefixMatch: /PREFIX
        routeAction:
          weightedBackendServices:
            - backendService: projects/PROJECT_ID/regions/us-west1/backendServices/green-service
              weight: 95
            - backendService: projects/PROJECT_ID/regions/us-west1/backendServices/blue-service
              weight: 5
    
  3. 使用 gcloud compute url-maps import 指令更新網址對應:

    gcloud compute url-maps import regional-lb-map \
       --region=us-west1 \
       --source=regional-lb-map-config.yaml
    

測試設定

如要測試設定,首先請確認傳送至先前設定的負載平衡器 IP 位址的要求,是由預設的 red 設定處理。

接著檢查並確認傳送至 FORWARDING_RULE_IP_ADDRESS/PREFIX 的要求是否如預期般拆分。

流量控管可讓您根據提供的 Cookie 來設定工作階段相依性。如要針對名為 red-service 的後端服務設定 HTTP_COOKIE 工作階段相依性,請按照下列指示操作。

  1. 使用 gcloud compute backend-services export 指令取得後端服務設定。

    gcloud compute backend-services export red-service \
        --destination=red-service-config.yaml \
        --region=us-west1
    
  2. 按照下列方式更新 red-service-config.yaml 檔案:

    sessionAffinity: 'HTTP_COOKIE'
    localityLbPolicy: 'RING_HASH'
    consistentHash:
     httpCookie:
      name: 'http_cookie'
      path: '/cookie_path'
      ttl:
        seconds: 100
        nanos: 500000000
     minimumRingSize: 10000
    
  3. red-service-config.yaml 檔案中,刪除下列程式碼行:

    sessionAffinity: NONE
    
  4. 更新後端服務設定檔:

    gcloud compute backend-services import red-service \
        --source=red-service-config.yaml \
        --region=us-west1
    

疑難排解

如果系統並未根據您設定的轉送規則和流量政策來轉送流量,請使用這項資訊進行故障排除。

如要進一步瞭解記錄和監控,請參閱外部 HTTP(S) 記錄與監控

問題:

  • 規則中的服務流量增加,而該項規則優於有問題的規則。
  • 指定轉送規則的 4xx 和 5xx HTTP 回應非預期增加。

解決方案:檢查轉送規則的順序。轉送規則會按照其指定順序進行解譯。

網址對應中的轉送規則會按照其指定順序進行解譯。這與根據最長前置字元相符項目解譯路徑規則的方式不同。如為路徑規則,則內部應用程式負載平衡器只會選取一個路徑規則。但是當您使用轉送規則時,可能會有多個規則均適用。

定義轉送規則時,請確認清單頂端的規則不會意外轉送原先會由後續轉送規則所轉送的流量。接收錯誤導向流量的服務可能會拒絕要求,且轉送規則中的服務所收到的流量會減少或完全沒有流量。

後續步驟