設定內部應用程式負載平衡器的流量管理

本文件將舉例說明如何針對特定用途使用流量管理功能。還有許多其他用途。

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

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

區域性外部應用程式負載平衡器與區域性內部應用程式負載平衡器。針對區域負載平衡器的流量管理設定,區域網址對應 API 區域後端服務 API 說明文件會提供完整的欄位清單,包括關於關係、限制和基數的語意。

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

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

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

除了本頁所述的進階轉送功能,支援的應用程式負載平衡器也整合了 Service Extensions,讓您在負載平衡資料路徑中插入自訂邏輯

事前準備

設定流量管理

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

如需編寫這些 YAML 檔案的相關說明,請參考本頁範例和 Cloud Load Balancing API 說明文件。

如要設定區域內部應用程式負載平衡器,您也可以使用 Google Cloud 控制台設定流量管理。

針對區域內部應用程式負載平衡器和區域外部應用程式負載平衡器,區域網址對應 API 區域後端服務 API 說明文件會提供完整的欄位清單,包括關於關係、限制和基數的語意。

在 Google Cloud 控制台中存取 YAML 範例

如何在 Google Cloud 控制台中存取 YAML 範例:

  1. 前往 Google Cloud 控制台的「Load balancing」(負載平衡)頁面。

    前往「Load balancing」(負載平衡) 頁面

  2. 點選「建立負載平衡器」
  3. 完成精靈的步驟,即可建立區域性內部應用程式負載平衡器。
  4. 在「轉送規則」設定中,選取「進階主機、路徑和轉送規則」
  5. 按一下「新增主機與路徑比對器」
  6. 按一下「Code guidance」連結。

系統會顯示「Path matcher YAML 範例」頁面。

將流量對應至單一服務

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

    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 的要求是否如預期般拆分。

建立用戶端 VM

相關操作說明請參閱「在區域中建立 VM 執行個體來測試連線能力」。

傳送要求給 FORWARDING_RULE_IP_ADDRESS

  1. 使用 ssh 連線至用戶端。

    gcloud compute ssh global-lb-client-us-west1-a \
       --zone=us-west1-a
    
  2. 執行下列指令:

    for LB_IP in FORWARDING_RULE_IP_ADDRESS; do
       RESULTS=
       for i in {1..1000}; do RESULTS="$RESULTS:`curl ${LB_IP}`"; done >/dev/null 2>&1
       IFS=':'
       echo "***"
       echo "*** Results of load balancing to $LB_IP: "
       echo "***"
       for line in $RESULTS; do echo $line; done | grep -Ev "^$" | sort | uniq -c
       echo
    done
    
查看結果
***
***Results of load balancing to FORWARDING_RULE_IP_ADDRESS:
***
502 red-instance-group-9jvq
498 red-instance-group-sww8

傳送要求給 FORWARDING_RULE_IP_ADDRESS/PREFIX

將要求傳送至 FORWARDING_RULE_IP_ADDRESS/PREFIX,並記下流量拆分。

for LB_IP in FORWARDING_RULE_IP_ADDRESS; do
    RESULTS=
    for i in {1..1000}; do RESULTS="$RESULTS:`curl ${LB_IP}/PREFIX/index.html`"; done >/dev/null 2>&1
    IFS=':'
    echo "***"
    echo "*** Results of load balancing to $LB_IP/PREFIX: "
    echo "***"
    for line in $RESULTS; do echo $line; done | grep -Ev "^$" | sort | uniq -c
    echo
done
查看結果
***
***Results of load balancing to FORWARDING_RULE_IP_ADDRESS/PREFIX:
***
21 blue-instance-group-8n49
27 blue-instance-group-vlqc
476 green-instance-group-c0wv
476 green-instance-group-rmf4

初期測試設定成功地將 95% 和 5% 的 /PREFIX 要求分別傳送至 greenblue 服務。

流量控管可讓您根據提供的 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 回應非預期增加。

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

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

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

後續步驟