為全域外部應用程式負載平衡器設定流量管理

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

這份文件包含全域外部應用程式負載平衡器的範例。全球外部應用程式負載平衡器會使用 EXTERNAL_MANAGED 負載平衡架構和全球負載平衡元件,例如轉送規則、網址對應和後端服務。

如要瞭解傳統版應用程式負載平衡器的流量管理功能,請參閱「傳統版應用程式負載平衡器的流量管理總覽」。

如要瞭解區域性外部應用程式負載平衡器的流量管理功能,請參閱「區域性外部應用程式負載平衡器的流量管理總覽」。

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

事前準備

請務必瞭解流量管理的運作方式。如需詳細資訊,請參閱「全域外部應用程式負載平衡器的流量管理總覽」。

設定及測試流量管理

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

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

不支援 Google Cloud 主控台。

全域網址對應 API 全域後端服務 API 說明文件會提供完整的欄位清單,包括關於關係、限制和基數的語意。

您可以為網址對應新增設定測試,確保網址對應能依預期轉送要求。您可以嘗試不同的網址對應規則,並視需要執行多項測試,確保對應會將流量轉送至適當的後端服務或後端值區。詳情請參閱「在網址對應中加入測試」。如要在不實際部署網址對應的情況下,測試對網址對應的新變更,請參閱「驗證網址對應設定」。

將流量對應至單一服務

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

    defaultService: projects/PROJECT_ID/global/backendServices/BACKEND_SERVICE_1
    hostRules:
    - hosts:
      - '*'
      pathMatcher: matcher1
    name: URL_MAP_NAME
    pathMatchers:
    - defaultService: projects/PROJECT_ID/global/backendServices/BACKEND_SERVICE_1
      name: matcher1
      routeRules:
      - matchRules:
        - prefixMatch: /PREFIX
        priority: PRIORITY  # 0 is highest
        routeAction:
          weightedBackendServices:
          - backendService: projects/PROJECT_ID/global/backendServices/BACKEND_SERVICE_1
            weight: 100

將流量拆分至兩項服務

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

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

設定網址重新導向

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

如要為後端值區建立重新導向,請將 defaultService 欄位設為 projects/PROJECT_ID/global/backendBuckets/BACKEND_BUCKET

   defaultService: projects/PROJECT_ID/global/backendServices/BACKEND_SERVICE_1
   name: <var>URL_MAP_NAME</var>
   hostRules:
   - hosts:
     - "HOST TO REDIRECT FROM" # Use * for all hosts
     pathMatcher: matcher1
   pathMatchers:
   - defaultService: projects/PROJECT_ID/global/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/global/backendServices/BACKEND_SERVICE_1
   name: global-lb-map
   hostRules:
   - hosts:
     - '*'
     pathMatcher: matcher1
   pathMatchers:
   - defaultService: projects/PROJECT_ID/global/backendServices/BACKEND_SERVICE_1
     name: matcher1
     routeRules:
       - matchRules:
           - prefixMatch: /PREFIX
         priority: PRIORITY  # 0 is highest
         routeAction:
           weightedBackendServices:
             - backendService: projects/PROJECT_ID/global/backendServices/BACKEND_SERVICE_1
               weight: 100
           requestMirrorPolicy:
             backendService: projects/PROJECT_ID/global/backendServices/BACKEND_SERVICE_2
             mirrorPercent: 50.0

如果您有多個權重後端服務,且想要記錄系統用來處理原始要求的後端服務,可以為所有要求新增包含這項資訊的自訂標頭。以下範例會在所有用戶端要求中新增名為 x-weighted-picked-backend 的自訂標頭。針對標頭值,請使用提供原始要求的後端服務名稱。

   defaultService: projects/PROJECT_ID/global/backendServices/BACKEND_SERVICE_1
   name: global-lb-map
   hostRules:
   - hosts:
     - '*'
     pathMatcher: matcher1
   pathMatchers:
   - defaultService: projects/PROJECT_ID/global/backendServices/BACKEND_SERVICE_1
     name: matcher1
     routeRules:
       - matchRules:
           - prefixMatch: /PREFIX
         priority: PRIORITY  # 0 is highest
         routeAction:
           weightedBackendServices:
            - backendService: projects/PROJECT_ID/global/backendServices/BACKEND_SERVICE_1
              weight: 95
              headerAction:
                requestHeadersToAdd:
                - headerName: x-weighted-picked-backend
                  headerValue: BACKEND_SERVICE_1
                  replace: True
            - backendService: projects/PROJECT_ID/global/backendServices/BACKEND_SERVICE_2
              weight: 5
              headerAction:
                requestHeadersToAdd:
                - headerName: x-weighted-picked-backend
                  headerValue: BACKEND_SERVICE_2
                  replace: True
           requestMirrorPolicy:
             backendService: projects/PROJECT_ID/global/backendServices/BACKEND_SERVICE_3

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

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

重新編寫要求的網址

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

   defaultService: projects/PROJECT_ID/global/backendServices/BACKEND_SERVICE_1
   name: global-lb-map
   hostRules:
   - hosts:
     - '*'
     pathMatcher: matcher1
   pathMatchers:
   - defaultService: projects/PROJECT_ID/global/backendServices/BACKEND_SERVICE_1
     name: matcher1
     routeRules:
       - matchRules:
           - prefixMatch: /PREFIX
         priority: PRIORITY  # 0 is highest
         routeAction:
           weightedBackendServices:
             - backendService: projects/PROJECT_ID/global/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/global/backendServices/BACKEND_SERVICE_1
   name: global-lb-map
   hostRules:
   - hosts:
     - '*'
     pathMatcher: matcher1
   pathMatchers:
   - defaultService: projects/PROJECT_ID/global/backendServices/BACKEND_SERVICE_1
     name: matcher1
     routeRules:
       - matchRules:
           - prefixMatch: /PREFIX
         priority: PRIORITY  # 0 is highest
         routeAction:
           weightedBackendServices:
             - backendService: projects/PROJECT_ID/global/backendServices/BACKEND_SERVICE_1
               weight: 100
           retryPolicy:
             retryConditions: 502, 504
             numRetries: 3
             perTryTimeout:
               seconds: 1
               nanos: 500000000

指定路徑逾時時間

指定所選路徑的逾時時間。系統會從要求完全處理完畢的時間開始計算逾時時間,直到回應完全處理完畢為止。逾時時間包括所有重試時間。請務必替換預留位置。

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

設定錯誤植入

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

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

設定 CORS

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

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

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

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

headerNameheaderValue 的有效值有限制。詳情請參閱「自訂標頭的運作方式」。

   defaultService: projects/PROJECT_ID/global/backendServices/BACKEND_SERVICE_1
   name: global-lb-map
   hostRules:
   - hosts:
     - '*'
     pathMatcher: matcher1
   pathMatchers:
   - defaultService: projects/PROJECT_ID/global/backendServices/BACKEND_SERVICE_1
     name: matcher1
     routeRules:
       - matchRules:
           - prefixMatch: /PREFIX
         priority: PRIORITY  # 0 is highest
         routeAction:
           weightedBackendServices:
             - backendService: projects/PROJECT_ID/global/backendServices/BACKEND_SERVICE_1
               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: EXTERNAL_MANAGED
    localityLbPolicy: RANDOM
    name: projects/PROJECT_ID/global/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

設定流量拆分:詳細步驟

本範例將示範以下步驟:

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

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

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

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

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

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

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

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

  • 使用路徑比對器。

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

定義服務

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

此處的操作說明假設您已建立 HTTP 健康狀態檢查 (global-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=EXTERNAL_MANAGED \
    --protocol=HTTP \
    --health-checks=global-lb-basic-check \
    --global \
  gcloud compute backend-services add-backend "${name}-service" \
    --balancing-mode='UTILIZATION' \
    --instance-group="${name}-instance-group" \
    --instance-group-zone="$zone" \
    --global)
}

建立服務

呼叫函式來提供 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

建立網址對應

主控台

  1. 前往 Google Cloud 控制台的「負載平衡」頁面。
    前往「負載平衡」
  2. 按一下「global-lb-map」連結。
  3. 按一下「編輯」圖示

設定新的轉送規則

  1. 在「轉送規則」下方,選取「進階主機、路徑和轉送規則」
  2. 在「New hosts and path matcher」下方,將「Service」設為 red-service,即可建立預設動作。
  3. 按一下 [完成]
  4. 按一下「新增主機與路徑比對器」
  5. 在「Hosts」欄位中,輸入負載平衡器轉送規則的 IP 位址。
  6. 將下列 YAML 內容貼到「路徑比對器」方塊中:

    defaultService: projects/PROJECT_ID/global/backendServices/red-service
    name: matcher1
    routeRules:
    - priority: 2
      matchRules:
        - prefixMatch: /PREFIX
      routeAction:
        weightedBackendServices:
          - backendService: projects/PROJECT_ID/global/backendServices/green-service
            weight: 95
          - backendService: projects/PROJECT_ID/global/backendServices/blue-service
            weight: 5
    
  7. 按一下 [完成]

  8. 按一下 [Update]

gcloud

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

    gcloud compute url-maps export global-lb-map \
      --destination=global-lb-map-config.yaml \
      --global
    
  2. 將下列內容新增至檔案結尾,即可更新網址對應檔案 global-lb-map-config.yaml

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

    gcloud compute url-maps import global-lb-map \
       --global \
       --source=global-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 \
        --global
    
  2. 請依照下列方式更新 red-service-config.yaml 檔案:

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

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

    gcloud compute backend-services import red-service \
        --source=red-service-config.yaml \
        --global
    

疑難排解

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

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

問題:

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

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

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

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

後續步驟