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

本文提供一些範例,說明如何使用 YAML 設定,在特定用途中管理流量。還有許多其他用途。

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

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

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

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

事前準備

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

設定及測試流量管理

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

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

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

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

使用 Google Cloud 控制台中的 YAML 範例

如要在 Google Cloud 控制台使用 YAML 範例,請按照下列步驟操作:

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

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

  2. 點選「建立負載平衡器」。
  3. 完成精靈的步驟,建立 global external Application Load Balancer。
  4. 在「Routing rules」(轉送規則) 設定中,選取「Advanced host and path rule」(進階主機和路徑規則)。
  5. 按一下「Add host and path rule」(新增主機與路徑規則)。
  6. 執行下列其中一個步驟:
    • 在「Path matcher」(路徑比對器) 方塊中,貼上本文件中的 YAML 範例。
    • 按一下「Code guidance」(程式碼指南) 連結。
    • 系統會顯示「Path matcher YAML examples」(路徑比對器 YAML 範例) 頁面。您可以將「路徑比對器 YAML 範例」頁面中的範例貼到「Path matcher」(路徑比對器) 方塊中。
  7. 按一下「完成」。

將流量對應至單一服務

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

    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 回應標頭,並按照重新導向動作中的指定內容,替換主機和路徑。

如要為後端 bucket 建立重新導向,請在 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

設定 Cloud CDN 快取政策

除了後端服務或後端 bucket 之外,您也可以在網址對應的不同層級設定 Cloud CDN 快取政策。您可以根據主機名稱、網址路徑、HTTP 標頭和查詢參數等條件,精細控管快取政策。

只要網址對應支援 routeAction 或 defaultRouteAction,您就能在任何位置設定一或多項快取政策。包括下列四個網址對應層級:

網址對應層級 API 何時會套用快取政策?
根層級 urlMap.defaultRouteAction.cachePolicy 如果要求的 hostname 與任何現有主機規則都不相符,就會套用這項設定。
路徑比對器 urlMap.pathMatchers[].defaultRouteAction.cachePolicy 如果要求的 hostname 符合主機規則,但沒有任何路徑規則或路由規則相符,就會套用這項規則。
路徑規則 urlMap.pathMatchers[].pathRules[].routeAction.cachePolicy 要求的路徑與路徑規則相符時套用。
路由規則 urlMap.pathMatchers[].routeRules[].routeAction.cachePolicy 如果要求的路徑符合路由規則的路徑、標頭或查詢參數條件,就會套用這項設定。

在網址對應中設定快取政策時,請注意下列事項:

  • 在網址對應的任何層級定義的快取政策,優先順序都高於後端針對特定路徑的 cdnPolicy。

  • 快取政策不會改用網址對應中較高層級定義的快取政策。舉例來說,如果要求符合特定 routeRule,但該沒有快取政策,負載平衡器不會改用 較高 pathMatcher 層級或根 urlMap 層級定義的快取政策。而是套用在後端服務或後端 bucket 上設定的 cdnPolicy 中定義的快取設定。

  • 經簽署的網址和動態壓縮只能在後端服務或後端 bucket 啟用,無法在網址對應中定義。要求送達時,負載平衡器會套用網址對應中定義的 cachePolicy。如果該要求轉送至設定了經簽署的網址或動態壓縮的後端服務或後端 bucket,系統會自動套用這些功能。因此,系統會結合網址對應的快取政策與後端的壓縮和經簽署的網址設定,決定要求的最終轉送和快取行為。

在下列網址對應的 YAML 設定中,快取政策是在根 urlMap 層級、pathMatchers 層級和 routeRules 層級設定。

網址對應層級 快取行為
routeRules

如果要求與 www.example.com 相符,且路徑與 /users/{username=*}/carts/{cartid=**} 模式相符,系統就會將要求轉送至 BACKEND_SERVICE_2。

針對這些要求,快取政策會設為 CACHE_ALL_STATIC,也就是說,圖片、CSS 和 JavaScript 等靜態內容會自動快取 1 小時 (3600 秒)。此外,這項設定也會明確設定 negative caching,將 404 Not Found 錯誤快取 5 分鐘 (300 秒)。

pathMatchers

如果要求符合 www.example.com,但路徑不符合 /users/{username=*}/carts/{cartid=**} 模式,要求就會轉送至 BACKEND_SERVICE_1。

這裡的快取政策設為 USE_ORIGIN_HEADERS,表示 Cloud CDN 會依據原始伺服器的 Cache-Control 標頭,判斷要快取的內容。cacheKeyPolicy 可確保系統根據通訊協定 (HTTP 與 HTTPS) 和特定主機名稱,建立不同的快取項目。

urlMap

如果要求的主機名稱完全不相符,系統會將要求轉送至網址對應的預設後端服務,也就是 BACKEND_SERVICE_DEFAULT。

快取政策設為 CACHE_ALL_STATIC,表示靜態內容會快取 1 小時 (3600 秒)。

defaultService: projects/PROJECT_ID/global/backendServices/BACKEND_SERVICE_DEFAULT
# This cache policy is applied if the request hostname does not match
# any hosts specified in the hostRules
defaultRouteAction:
  cachePolicy:
    cacheMode: CACHE_ALL_STATIC
    defaultTtl:
      seconds: 3600
    negativeCaching: true
hostRules:
- hosts:
  - www.example.com
  pathMatcher: cart-matcher
pathMatchers:
- name: cart-matcher
  defaultService: projects/PROJECT_ID/global/backendServices/BACKEND_SERVICE_1
  # This cache policy is applied if there is a host match but no specific route rule match.
  defaultRouteAction:
    cachePolicy:
      cacheMode: USE_ORIGIN_HEADERS
      cacheKeyPolicy:
        includeProtocol: true
        includeHost: true
  routeRules:
  - description: CartService
    matchRules:
      - pathTemplateMatch: '/users/{username=*}/carts/{cartid=**}'
    service: projects/PROJECT_ID/global/backendServices/BACKEND_SERVICE_2
    priority: PRIORITY  # 0 is highest
    # This cache policy is applied if there is a route rule match.
    routeAction:
      cachePolicy:
        cacheMode: CACHE_ALL_STATIC
        defaultTtl:
          seconds: 3600
        negativeCaching: true
        negativeCachingPolicy:
          - code: 404
            ttl:
             seconds: 300

如要在網址對應的不同層級設定及管理快取政策,請參閱「設定 Cloud CDN 快取政策」。

設定 CORS

設定跨源資源共享 (CORS) 政策,控管負載平衡器處理跨來源要求的方式。

在路徑比對器層級套用 CORS 政策

在這項設定中,CORS 政策是在路徑比對器 (pathMatchers[].defaultRouteAction.corsPolicy) 的 defaultRouteAction 中定義。這表示無論特定路徑或路由為何,政策都會套用至透過預設路徑比對器轉送的所有要求。

如果想為路徑比對器管理的所有路徑,採用單一且一致的 CORS 政策,就適合使用這個方法。

defaultService: https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/backendServices/BACKEND_SERVICE_1
name: global-lb-map
hostRules:
- hosts:
  - '*'
  pathMatcher: path-matcher-1
pathMatchers:
- defaultService: https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/backendServices/BACKEND_SERVICE_1
  name: path-matcher-1
- defaultRouteAction:
    corsPolicy:
      allowCredentials: true
      allowOrigins: [ "http://example.com" ]
      allowMethods: [ "GET", "POST" ]
      allowHeaders: [ "Authorization", "Content-Type" ]

運作方式

  • 負載平衡器會對路徑比對器處理的所有要求強制執行 CORS 政策。
  • 只有來自 example.com 主機、使用 GET 或 POST 方法,且具有允許標頭 (Authorization、Content-Type) 的要求,才會獲得允許。
  • 允許在跨來源要求中使用憑證 (例如 Cookie 或授權標頭)。
  • 後端服務只會接收符合這項 CORS 政策的要求。

在路由規則層級套用 CORS 政策

在這個設定中,CORS 政策是在特定路由規則 (pathMatchers[].routeRules[].routeAction.corsPolicy) 的 routeAction 中定義。這樣一來,您就能將不同的 CORS 政策套用至不同的路由或路徑前置字串。

如果需要精細控管,例如對不同的 API 端點或路徑套用不同的 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://example.com" ]
               allowMethods: [ "GET", "POST" ]
               allowHeaders: [ "Authorization", "Content-Type" ]
               maxAge: 1200
               allowCredentials: true

運作方式

  • CORS 政策只會對符合指定路徑前置字元 (例如 /PREFIX) 的要求強制執行。
  • 這條路徑只允許來自 example.com 主機、使用 GET 或 POST 方法,且具有允許標頭的要求。
  • maxAge 欄位會指定瀏覽器可以快取預檢要求結果的時間長度 (以秒為單位)。
  • 跨來源要求允許憑證。
  • 其他路徑可以有不同的 CORS 政策,或完全沒有政策。

您也可以在網址對應的下列層級定義 CORS 政策:

  • defaultRouteAction.corsPolicy
  • pathMatchers[].pathRules[].routeAction.corsPolicy

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

在將要求傳送至後端服務之前,新增及移除要求標頭。此外,您也可以在收到後端服務的回應後,新增及移除回應標頭。

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

   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

斷路機制

全域外部應用程式負載平衡器不支援設定斷路器 (circuitBreakers)。區域性外部應用程式負載平衡器和區域性內部應用程式負載平衡器支援斷路功能。如要保護後端服務,避免全域外部應用程式負載平衡器超載,請設定 Google Cloud Armor 頻率限制和後端服務平衡模式容量控制項 (最大頻率或最大使用率)。

設定流量拆分:詳細步驟

本範例將示範以下步驟:

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

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

  3. 建立路由規則,設定 95% / 5% 的流量拆分。

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

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

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

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

  • 您設定了替代路徑,將 5% 的流量傳送至 blue-service,95% 的流量傳送至 green-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)
}

建立服務

呼叫函式,建立 red、green 和 blue 三項服務。red 服務會做為傳送至 / 的要求的預設服務。green 和 blue 服務都設定在 /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 控制台的「Load balancing」(負載平衡) 頁面。
    前往「Load balancing」(負載平衡)
  2. 點選「global-lb-map」連結。
  3. 按一下「編輯」圖示 。

設定新的路由規則

  1. 在「轉送規則」下方,選取「進階型主機與路徑規則」。
  2. 在「New hosts and path matcher」(新增主機和路徑比對器) 下方,將「Service」(服務) 設為 red-service,建立預設動作。
  3. 按一下「完成」。
  4. 按一下「Add hosts and path rule」(新增主機和路徑規則)。
  5. 在「Hosts」(主機) 欄位中,輸入負載平衡器轉送規則的 IP 位址。
  6. 在「Path matcher」(路徑比對器) 方塊中,貼上下列 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 回應異常增加。

解決方法:檢查路由規則的順序。系統會按照指定順序解讀路由規則。

系統會按照指定順序解讀網址對應中的路由規則。這與根據最長前置字元相符項目解譯路徑規則的方式不同。如果是路徑規則,全域外部應用程式負載平衡器只會選取單一路徑規則;不過,如果使用路由規則,則可能套用多個規則。

定義路由規則時,請確認清單頂端的規則不會不小心轉送流量,否則流量會由後續的路由規則轉送。接收到錯誤導向流量的服務可能會拒絕要求,而路由規則中的服務則會收到較少流量,或完全沒有流量。

後續步驟