使用 VM 執行個體群組後端設定跨區域內部應用程式負載平衡器

本文件將針對在 Compute Engine 虛擬機器 (VM) 執行個體中執行的服務,提供如何設定跨區域內部應用程式負載平衡器的操作說明。

事前準備

在您依循這份指南操作之前,請先熟悉以下概念:

設定 SSL 憑證資源

請按照下列說明建立 Certificate Manager SSL 憑證資源:

建議使用 Google 代管的憑證。

權限

如要依照本指南的說明操作,您必須能在專案中建立執行個體與修改網路。您必須是專案擁有者或編輯者,或是必須具有以下所有 Compute Engine 身分與存取權管理角色

工作 必要角色
建立網路、子網路和負載平衡器元件 Compute 網路管理員
新增與移除防火牆規則 Compute 安全管理員
建立執行個體 Compute 執行個體管理員

詳情請參閱下列指南:

設定總覽

您可以設定負載平衡器,如以下圖表所示:

跨區域內部應用程式負載平衡器高可用性部署。
跨區域內部應用程式負載平衡器高可用性部署 (按一下可放大)。

如圖所示,這個範例在虛擬私有雲網路中建立跨區域內部應用程式負載平衡器,其中在 REGION_AREGION_B 區域中,分別有一個後端服務和兩個後端代管執行個體群組。

下圖顯示以下內容:

  1. 具有下列子網路的虛擬私有雲網路:

    • 子網路 SUBNET_AREGION_A 中的 Proxy 專用子網路。
    • 子網路 SUBNET_BREGION_B 中的 Proxy 專用子網路。

    您必須在使用跨區域內部應用程式負載平衡器的虛擬私有雲網路的每個地區,建立僅限 Proxy 的子網路。該地區的僅限 Proxy 子網路會在該地區的所有跨區域內部應用程式負載平衡器之間共用。系統會從僅限 Proxy 的子網路中分配從負載平衡器傳送至服務後端的封包來源位址。在這個範例中,該地區的僅限 Proxy 子網路的主要 IP 位址範圍為 10.129.0.0/23,而 REGION_B 的主要 IP 位址範圍為 10.130.0.0/23,這是建議的子網路大小。REGION_A

  2. 高可用性設定會為 REGION_AREGION_B 區域中的 Compute Engine VM 部署作業提供代管執行個體群組後端。如果某個區域的後端發生故障,流量就會移轉至其他區域。

  3. 監控後端使用情況和健康狀態的全域後端服務。

  4. 全域網址對應,這項服務會剖析要求的網址,並根據要求網址的主機和路徑,將要求轉送至特定的後端服務。

  5. 全球目標 HTTP 或 HTTPS Proxy,會接收使用者的要求,並將其轉送至網址對應。如為 HTTPS,請設定全域安全資料傳輸層 (SSL) 憑證資源。如果您設定了 HTTPS 負載平衡,目標 Proxy 會使用 SSL 憑證來解密 SSL 流量。目標 Proxy 可使用 HTTP 或 HTTPS 將流量轉送至您的執行個體。

  6. 全域轉送規則,具有負載平衡器的區域內部 IP 位址,可將每個傳入要求轉送至目標 Proxy。

    與轉送規則相關聯的內部 IP 位址,可以來自與後端相同網路和地區的子網路。請注意下列條件:

    • IP 位址可以 (但不必) 與後端執行個體群組位於相同的子網路。
    • IP 位址不得來自保留的僅限 Proxy 子網路,且其 --purpose 標記必須設為 GLOBAL_MANAGED_PROXY
    • 如果您想使用相同的內部 IP 位址搭配多個轉送規則,請將 IP 位址 --purpose 標記設為 SHARED_LOADBALANCER_VIP
  7. 選用:設定 DNS 轉送政策,類型為 GEO,將用戶端流量轉送至離用戶端最近的地區中負載平衡器 VIP。

設定網路和子網路

在虛擬私有雲網路中,針對已設定後端的每個區域設定子網路。此外,請在您要設定負載平衡器的每個區域中設定 proxy-only-subnet

這個範例會使用以下虛擬私人雲端網路、地區和子網路:

  • 聯播網。網路是名為 NETWORK自訂模式虛擬私人雲端網路

  • 後端的子網路

    • REGION_A 地區中名為 SUBNET_A 的子網路使用 10.1.2.0/24 做為其主要 IP 範圍。
    • REGION_B 地區中名為 SUBNET_B 的子網路使用 10.1.3.0/24 做為其主要 IP 範圍。
  • Proxy 專用子網路

    • REGION_A 地區中名為 PROXY_SN_A 的子網路使用 10.129.0.0/23 做為其主要 IP 範圍。
    • REGION_B 地區中名為 PROXY_SN_B 的子網路使用 10.130.0.0/23 做為其主要 IP 範圍。

跨區域內部應用程式負載平衡器可從 VPC 中的任何區域存取。因此,來自任何區域的用戶端都能在全球範圍內存取負載平衡器後端。

設定後端子網路

主控台

  1. 在 Google Cloud 控制台中,前往「VPC Networks」(虛擬私有雲網路) 頁面。

    前往「VPC networks」(虛擬私有雲網路)

  2. 按一下「建立虛擬私有雲網路」

  3. 提供網路的「名稱」

  4. 在「子網路」部分,將「子網路建立模式」設為「自訂」

  5. 為負載平衡器的後端建立子網路。在「New subnet」(新的子網路) 區段中,輸入以下資訊:

    • 提供這個子網路的 [Name] (名稱)
    • 選取「區域」REGION_A
    • 輸入「IP 位址範圍」10.1.2.0/24
  6. 按一下 [完成]

  7. 按一下 [新增子網路]

  8. 為負載平衡器的後端建立子網路。在「New subnet」(新的子網路) 區段中,輸入以下資訊:

    • 提供這個子網路的 [Name] (名稱)
    • 選取「區域」REGION_B
    • 輸入「IP 位址範圍」10.1.3.0/24
  9. 按一下 [完成]

  10. 按一下 [建立]。

gcloud

  1. 使用 gcloud compute networks create 指令建立自訂虛擬私有雲網路:

    gcloud compute networks create NETWORK \
        --subnet-mode=custom
    
  2. 使用 gcloud compute networks subnets create 指令,在 REGION_A 地區的 NETWORK 網路中建立子網路:

    gcloud compute networks subnets create SUBNET_A \
        --network=NETWORK \
        --range=10.1.2.0/24 \
        --region=REGION_A
    
  3. 使用 gcloud compute networks subnets create 指令,在 REGION_B 地區的 NETWORK 網路中建立子網路:

    gcloud compute networks subnets create SUBNET_B \
        --network=NETWORK \
        --range=10.1.3.0/24 \
        --region=REGION_B
    

Terraform

如要建立虛擬私有雲網路,請使用 google_compute_network 資源

resource "google_compute_network" "default" {
  auto_create_subnetworks = false
  name                    = "lb-network-crs-reg"
  provider                = google-beta
}

如要在 lb-network-crs-reg 網路中建立 VPC 子網路,請使用 google_compute_subnetwork 資源

resource "google_compute_subnetwork" "subnet_a" {
  provider      = google-beta
  ip_cidr_range = "10.1.2.0/24"
  name          = "lbsubnet-uswest1"
  network       = google_compute_network.default.id
  region        = "us-west1"
}
resource "google_compute_subnetwork" "subnet_b" {
  provider      = google-beta
  ip_cidr_range = "10.1.3.0/24"
  name          = "lbsubnet-useast1"
  network       = google_compute_network.default.id
  region        = "us-east1"
}

API

networks.insert 方法提出 POST 要求。將 PROJECT_ID 替換為您的專案 ID。

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/networks

{
 "routingConfig": {
   "routingMode": "regional"
 },
 "name": "NETWORK",
 "autoCreateSubnetworks": false
}

subnetworks.insert 方法提出 POST 要求。將 PROJECT_ID 替換為您的專案 ID。

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION_A/subnetworks

{
 "name": "SUBNET_A",
 "network": "projects/PROJECT_ID/global/networks/lb-network-crs-reg",
 "ipCidrRange": "10.1.2.0/24",
 "region": "projects/PROJECT_ID/regions/REGION_A",
}

subnetworks.insert 方法提出 POST 要求。將 PROJECT_ID 替換為您的專案 ID。

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION_B/subnetworks

{
 "name": "SUBNET_B",
 "network": "projects/PROJECT_ID/global/networks/NETWORK",
 "ipCidrRange": "10.1.3.0/24",
 "region": "projects/PROJECT_ID/regions/REGION_B",
}

設定僅限 Proxy 的子網路

僅限 Proxy 子網路會提供一組 IP 位址, Google Cloud 用於代表您執行 Envoy Proxy。Proxy 會終止來自用戶端的連線,並建立連至後端的新連線。

這個僅限 Proxy 的子網路會由與虛擬私有雲網路位於同一個區域的所有 Envoy 型區域負載平衡器使用。每個地區和每個網路只能有一個用於特定用途的活動的僅限 Proxy 子網路。

控制台

如果您使用的是 Google Cloud 主控台,可以等之後再於「負載平衡」頁面中建立僅限 Proxy 的子網路。

如果您現在想建立僅限 Proxy 的子網路,請按照下列步驟操作:

  1. 在 Google Cloud 控制台中,前往「VPC Networks」(虛擬私有雲網路) 頁面。

    前往「VPC networks」(虛擬私有雲網路)

  2. 按一下虛擬私有雲網路的名稱。
  3. 在「子網路」分頁中,按一下「新增子網路」
  4. 提供僅限 Proxy 子網路的「名稱」
  5. 選取「區域」REGION_A
  6. 在「用途」清單中,選取「跨區域的 Managed Proxy」
  7. 在「IP address range」欄位中輸入 10.129.0.0/23
  8. 按一下「新增」。

REGION_B 中建立僅限 Proxy 的子網路

  1. 在「子網路」分頁中,按一下「新增子網路」
  2. 提供僅限 Proxy 子網路的「名稱」
  3. 選取「區域」REGION_B
  4. 在「用途」清單中,選取「跨區域的 Managed Proxy」
  5. 在「IP address range」欄位中輸入 10.130.0.0/23
  6. 按一下「新增」。

gcloud

使用 gcloud compute networks subnets create 指令建立僅限 Proxy 的子網路。

    gcloud compute networks subnets create PROXY_SN_A \
        --purpose=GLOBAL_MANAGED_PROXY \
        --role=ACTIVE \
        --region=REGION_A \
        --network=NETWORK \
        --range=10.129.0.0/23
    
    gcloud compute networks subnets create PROXY_SN_B \
        --purpose=GLOBAL_MANAGED_PROXY \
        --role=ACTIVE \
        --region=REGION_B \
        --network=NETWORK \
        --range=10.130.0.0/23
    

Terraform

如要在 lb-network-crs-reg 網路中建立僅限 Proxy 的 VPC 子網路,請使用 google_compute_subnetwork 資源

resource "google_compute_subnetwork" "proxy_subnet_a" {
  provider      = google-beta
  ip_cidr_range = "10.129.0.0/23"
  name          = "proxy-only-subnet1"
  network       = google_compute_network.default.id
  purpose       = "GLOBAL_MANAGED_PROXY"
  region        = "us-west1"
  role          = "ACTIVE"
  lifecycle {
    ignore_changes = [ipv6_access_type]
  }
}
resource "google_compute_subnetwork" "proxy_subnet_b" {
  provider      = google-beta
  ip_cidr_range = "10.130.0.0/23"
  name          = "proxy-only-subnet2"
  network       = google_compute_network.default.id
  purpose       = "GLOBAL_MANAGED_PROXY"
  region        = "us-east1"
  role          = "ACTIVE"
  lifecycle {
    ignore_changes = [ipv6_access_type]
  }
}

API

使用 subnetworks.insert 方法建立僅限 Proxy 的子網路,並將 PROJECT_ID 替換為您的專案 ID。

    POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION_A/subnetworks

    {
      "name": " PROXY_SN_A",
      "ipCidrRange": "10.129.0.0/23",
      "network": "projects/PROJECT_ID/global/networks/NETWORK",
      "region": "projects/PROJECT_ID/regions/REGION_A",
      "purpose": "GLOBAL_MANAGED_PROXY",
      "role": "ACTIVE"
    }
   
    POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION_B/subnetworks

    {
      "name": "PROXY_SN_B",
      "ipCidrRange": "10.130.0.0/23",
      "network": "projects/PROJECT_ID/global/networks/NETWORK",
      "region": "projects/PROJECT_ID/regions/REGION_B",
      "purpose": "GLOBAL_MANAGED_PROXY",
      "role": "ACTIVE"
    }
   

設定防火牆規則

這個範例使用以下防火牆規則:

  • fw-ilb-to-backends. 輸入規則,適用於要進行負載平衡的執行個體,可在 TCP 通訊埠 22 上允許來自任何位址的連入 SSH 連線。您可以為這項規則選擇較嚴格的來源 IP 位址範圍;例如,您可以僅指定要從其中啟動 SSH 工作階段之系統的 IP 位址範圍。這個範例會使用目標標記 allow-ssh 來辨識套用防火牆規則的 VM。

  • fw-healthcheck。輸入規則,適用於要進行負載平衡的執行個體,可允許來自 Google Cloud健康狀態檢查系統 (在 130.211.0.0/2235.191.0.0/16 中) 的所有 TCP 流量。這個範例會使用目標標記 load-balanced-backend 來辨識套用防火牆規則的 VM。

  • fw-backends。輸入規則,適用於要進行負載平衡的執行個體,可在 804438080 通訊埠上允許來自內部應用程式負載平衡器代管 Proxy 的 TCP 流量。這個範例會使用目標標記 load-balanced-backend 來辨識套用防火牆規則的 VM。

如果沒有這些防火牆規則,預設拒絕輸入規則將會封鎖傳入至後端執行個體的流量。

目標代碼定義後端執行個體。如未指定目標標記,防火牆規則會套用至 VPC 網路中的所有後端執行個體。建立後端 VM 時,請務必加入指定的目標標記,如「建立代管執行個體群組」一文所示。

主控台

  1. 在 Google Cloud 控制台中,前往「Firewall policies」(防火牆政策) 頁面。

    前往「防火牆政策」

  2. 按一下「Create firewall rule」(建立防火牆規則),建立允許連入 SSH 連線的規則:

    • Name (名稱):fw-ilb-to-backends
    • Network (網路):NETWORK
    • Direction of traffic (流量方向):「Ingress」(輸入)
    • 「Action on match」(相符時執行的動作)「Allow」(允許)
    • 目標指定的目標標記
    • 「Target tags」(目標標記)allow-ssh
    • 來源篩選器IPv4 範圍
    • Source IPv4 ranges (來源 IPv4 範圍):0.0.0.0/0
    • 通訊協定和通訊埠
      • 選擇「Specified protocols and ports」
      • 勾選「TCP」核取方塊,然後輸入 22 做為「Port number」(通訊埠編號)。
  3. 按一下 [建立]。

  4. 再次按一下「Create firewall rule」(建立防火牆規則),建立允許Google Cloud 健康狀態檢查的規則:

    • Name (名稱):fw-healthcheck
    • Network (網路):NETWORK
    • Direction of traffic (流量方向):「Ingress」(輸入)
    • 「Action on match」(相符時執行的動作)「Allow」(允許)
    • 目標指定的目標標記
    • 「Target tags」(目標標記)load-balanced-backend
    • 來源篩選器IPv4 範圍
    • Source IPv4 ranges (來源 IPv4 範圍):130.211.0.0/2235.191.0.0/16
    • 通訊協定和通訊埠

      • 選擇「Specified protocols and ports」
      • 勾選「TCP」核取方塊,然後輸入 80 做為「Port number」(通訊埠編號)。

      最佳做法是將此規則限制為僅適用於與健康檢查所用通訊協定和通訊埠相符的項目。如果您將 tcp:80 用於通訊協定和通訊埠, Google Cloud 可以使用通訊埠 80 的 HTTP 與 VM 聯絡,但無法使用通訊埠 443 的 HTTPS 與 VM 聯絡。

  5. 按一下 [建立]。

  6. 第三次按一下「Create firewall rule」(建立防火牆規則),以建立允許負載平衡器 Proxy 伺服器連結後端的規則:

    • Name (名稱):fw-backends
    • Network (網路):NETWORK
    • Direction of traffic (流量方向):「Ingress」(輸入)
    • 「Action on match」(相符時執行的動作)「Allow」(允許)
    • 目標指定的目標標記
    • 「Target tags」(目標標記)load-balanced-backend
    • 來源篩選器IPv4 範圍
    • Source IPv4 ranges (來源 IPv4 範圍):10.129.0.0/2310.130.0.0/23
    • 通訊協定和通訊埠
      • 選擇「Specified protocols and ports」
      • 勾選「TCP」TCP核取方塊,然後輸入 80, 443, 8080 做為「Port number」(通訊埠編號)。
  7. 按一下 [建立]。

gcloud

  1. 建立 fw-ilb-to-backends 防火牆規則,允許與具有 allow-ssh 網路標記的 VM 建立 SSH 連線。若省略 source-ranges,Google Cloud 會將規則解讀為任何來源

    gcloud compute firewall-rules create fw-ilb-to-backends \
        --network=NETWORK \
        --action=allow \
        --direction=ingress \
        --target-tags=allow-ssh \
        --rules=tcp:22
    
  2. 建立 fw-healthcheck 規則,允許 Google Cloud健康狀態檢查。這個範例可允許來自健康狀態檢查探測器的所有 TCP 流量,但您可以根據自己的需求設定一組較少的通訊埠。

    gcloud compute firewall-rules create fw-healthcheck \
        --network=NETWORK \
        --action=allow \
        --direction=ingress \
        --source-ranges=130.211.0.0/22,35.191.0.0/16 \
        --target-tags=load-balanced-backend \
        --rules=tcp
    
  3. 建立 fw-backends 規則,允許內部應用程式負載平衡器的 Proxy 連結後端。將 source-ranges 設為僅限 Proxy 子網路的已分配範圍,例如 10.129.0.0/2310.130.0.0/23

    gcloud compute firewall-rules create fw-backends \
        --network=NETWORK \
        --action=allow \
        --direction=ingress \
        --source-ranges=source-range \
        --target-tags=load-balanced-backend \
        --rules=tcp:80,tcp:443,tcp:8080
    

Terraform

如要建立防火牆規則,請使用 google_compute_firewall 資源

resource "google_compute_firewall" "fw_healthcheck" {
  name          = "gl7-ilb-fw-allow-hc"
  provider      = google-beta
  direction     = "INGRESS"
  network       = google_compute_network.default.id
  source_ranges = ["130.211.0.0/22", "35.191.0.0/16", "35.235.240.0/20"]
  allow {
    protocol = "tcp"
  }
}
resource "google_compute_firewall" "fw_ilb_to_backends" {
  name          = "fw-ilb-to-fw"
  provider      = google-beta
  network       = google_compute_network.default.id
  source_ranges = ["0.0.0.0/0"]
  allow {
    protocol = "tcp"
    ports    = ["22", "80", "443", "8080"]
  }
}
resource "google_compute_firewall" "fw_backends" {
  name          = "gl7-ilb-fw-allow-ilb-to-backends"
  direction     = "INGRESS"
  network       = google_compute_network.default.id
  source_ranges = ["10.129.0.0/23", "10.130.0.0/23"]
  target_tags   = ["http-server"]
  allow {
    protocol = "tcp"
    ports    = ["80", "443", "8080"]
  }
}

API

請向 firewalls.insert 方法提出 POST 要求,並將 PROJECT_ID 替換為您的專案 ID,藉此建立 fw-ilb-to-backends 防火牆規則。

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/firewalls

{
 "name": "fw-ilb-to-backends",
 "network": "projects/PROJECT_ID/global/networks/NETWORK",
 "sourceRanges": [
   "0.0.0.0/0"
 ],
 "targetTags": [
   "allow-ssh"
 ],
 "allowed": [
  {
    "IPProtocol": "tcp",
    "ports": [
      "22"
    ]
  }
 ],
"direction": "INGRESS"
}

請向 firewalls.insert 方法提出 POST 要求,並將 PROJECT_ID 替換為您的專案 ID,藉此建立 fw-healthcheck 防火牆規則。

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/firewalls

{
 "name": "fw-healthcheck",
 "network": "projects/PROJECT_ID/global/networks/NETWORK",
 "sourceRanges": [
   "130.211.0.0/22",
   "35.191.0.0/16"
 ],
 "targetTags": [
   "load-balanced-backend"
 ],
 "allowed": [
   {
     "IPProtocol": "tcp"
   }
 ],
 "direction": "INGRESS"
}

建立 fw-backends 防火牆規則,允許代理子網路中的 TCP 流量,適用於 firewalls.insert 方法,並將 PROJECT_ID 替換為您的專案 ID。

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/firewalls

{
 "name": "fw-backends",
 "network": "projects/PROJECT_ID/global/networks/NETWORK",
 "sourceRanges": [
   "10.129.0.0/23",
   "10.130.0.0/23"
 ],
 "targetTags": [
   "load-balanced-backend"
 ],
 "allowed": [
   {
     "IPProtocol": "tcp",
     "ports": [
       "80"
     ]
   },
 {
     "IPProtocol": "tcp",
     "ports": [
       "443"
     ]
   },
   {
     "IPProtocol": "tcp",
     "ports": [
       "8080"
     ]
   }
 ],
 "direction": "INGRESS"
}

建立代管執行個體群組

本節說明如何建立範本和代管執行個體群組。代管執行個體群組提供的 VM 執行個體,會執行跨區域內部應用程式負載平衡器範例的後端伺服器。針對執行個體群組,您可以定義 HTTP 服務,並將通訊埠名稱對應至相關的通訊埠。負載平衡器的後端服務會將流量轉送至具名通訊埠。從用戶端到後端伺服器的流量會經過負載平衡。為示範之用,後端會提供自己的主機名稱。

主控台

  1. 在 Google Cloud 控制台中,前往「Instance templates」(執行個體範本) 頁面。

    前往「Instance templates」(執行個體範本) 頁面

    1. 點選「建立執行個體範本」
    2. 在「Name」(名稱) 中輸入 gil7-backendeast1-template
    3. 確認「開機磁碟」已設為 Debian 映像檔,例如「Debian GNU/Linux 12 (bookworm)」。這些操作說明使用僅在 Debian 上可用的指令,例如 apt-get
    4. 點選「進階選項」
    5. 按一下「網路」,然後設定下列欄位:
      1. 在「Network tags」(網路標記) 中輸入 allow-sshload-balanced-backend
      2. 在「網路介面」中,選取下列項目:
        • Network (網路):NETWORK
        • Subnet (子網路):SUBNET_B
    6. 按一下 [Management] (管理)。在「Startup script」(開機指令碼) 欄位中輸入下列指令碼。

      #! /bin/bash
      apt-get update
      apt-get install apache2 -y
      a2ensite default-ssl
      a2enmod ssl
      vm_hostname="$(curl -H "Metadata-Flavor:Google" \
      http://169.254.169.254/computeMetadata/v1/instance/name)"
      echo "Page served from: $vm_hostname" | \
      tee /var/www/html/index.html
      systemctl restart apache2
      
    7. 按一下 [建立]。

    8. 點選「建立執行個體範本」

    9. 在「Name」(名稱) 中輸入 gil7-backendwest1-template

    10. 確認「開機磁碟」已設為 Debian 映像檔,例如「Debian GNU/Linux 12 (bookworm)」。這些操作說明使用僅在 Debian 上可用的指令,例如 apt-get

    11. 點選「進階選項」

    12. 按一下「網路」,然後設定下列欄位:

      1. 在「Network tags」(網路標記) 中輸入 allow-sshload-balanced-backend
      2. 在「網路介面」中,選取下列項目:
        • Network (網路):NETWORK
        • Subnet (子網路):SUBNET_A
    13. 按一下 [Management] (管理)。在「Startup script」(開機指令碼) 欄位中輸入下列指令碼。

      #! /bin/bash
      apt-get update
      apt-get install apache2 -y
      a2ensite default-ssl
      a2enmod ssl
      vm_hostname="$(curl -H "Metadata-Flavor:Google" \
      http://169.254.169.254/computeMetadata/v1/instance/name)"
      echo "Page served from: $vm_hostname" | \
      tee /var/www/html/index.html
      systemctl restart apache2
      
    14. 按一下 [建立]。

  2. 前往 Google Cloud 控制台的「Instance groups」(執行個體群組) 頁面。

    前往「Instance groups」(執行個體群組)

    1. 點選「建立執行個體群組」
    2. 選取「New managed instance group (stateless)」(新增代管執行個體群組 (無狀態))。詳情請參閱「無狀態或有狀態的 MIG」。
    3. 在「Name」(名稱) 中輸入 gl7-ilb-mig-a
    4. 在「Location」(位置) 中,選取「Single zone」(單一可用區)
    5. 在「Region」(區域) 中選取 REGION_A
    6. 在「Zone」(區域) 中選取 ZONE_A
    7. 在「Instance template」(執行個體範本) 中選取 gil7-backendwest1-template
    8. 指定要在群組中建立的執行個體數量。

      在本例中,請在「Autoscaling」(自動調度資源) 下指定下列選項:

      • 針對「Autoscaling mode」(自動調度資源模式),選取 Off:do not autoscale
      • 在「Maximum number of instances」(執行個體數量上限) 中輸入 2

      您也可以根據需要,在 UI 的「Autoscaling」(自動調度資源) 區段中,將執行個體群組設為根據執行個體 CPU 使用量自動新增或移除執行個體

    9. 按一下 [建立]。

    10. 點選「建立執行個體群組」

    11. 選取「New managed instance group (stateless)」(新增代管執行個體群組 (無狀態))。詳情請參閱「無狀態或有狀態的 MIG」。

    12. 在「Name」(名稱) 中輸入 gl7-ilb-mig-b

    13. 在「Location」(位置) 中,選取「Single zone」(單一可用區)

    14. 在「Region」(區域) 中選取 REGION_B

    15. 在「Zone」(區域) 中選取 ZONE_B

    16. 在「Instance template」(執行個體範本) 中選取 gil7-backendeast1-template

    17. 指定要在群組中建立的執行個體數量。

      在本例中,請在「Autoscaling」(自動調度資源) 下指定下列選項:

      • 針對「Autoscaling mode」(自動調度資源模式),選取 Off:do not autoscale
      • 在「Maximum number of instances」(執行個體數量上限) 中輸入 2

      您也可以根據需要,在 UI 的「Autoscaling」(自動調度資源) 區段中,將執行個體群組設為根據執行個體 CPU 使用量自動新增或移除執行個體

    18. 按一下 [建立]。

gcloud

本指南的 gcloud CLI 操作說明假設您使用 Cloud Shell 或已安裝 bash 的其他環境。

  1. 使用 gcloud compute instance-templates create 指令,建立含有 HTTP 伺服器的 VM 執行個體範本。

    gcloud compute instance-templates create gil7-backendwest1-template \
      --region=REGION_A \
      --network=NETWORK \
      --subnet=SUBNET_A \
      --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
        vm_hostname="$(curl -H "Metadata-Flavor:Google" \
        http://169.254.169.254/computeMetadata/v1/instance/name)"
        echo "Page served from: $vm_hostname" | \
        tee /var/www/html/index.html
        systemctl restart apache2'
    
    gcloud compute instance-templates create gil7-backendeast1-template \
        --region=REGION_B \
        --network=NETWORK \
        --subnet=SUBNET_B \
        --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
          vm_hostname="$(curl -H "Metadata-Flavor:Google" \
          http://169.254.169.254/computeMetadata/v1/instance/name)"
          echo "Page served from: $vm_hostname" | \
          tee /var/www/html/index.html
          systemctl restart apache2'
    
  2. 使用 gcloud compute instance-groups managed create 指令,在區域中建立代管執行個體群組。

    gcloud compute instance-groups managed create gl7-ilb-mig-a \
        --zone=ZONE_A \
        --size=2 \
        --template=gil7-backendwest1-template
    
    gcloud compute instance-groups managed create gl7-ilb-mig-b \
        --zone=ZONE_B \
        --size=2 \
        --template=gil7-backendeast1-template
    

Terraform

如要建立執行個體範本,請使用 google_compute_instance_template 資源

resource "google_compute_instance_template" "instance_template_a" {
  name         = "gil7-backendwest1-template"
  provider     = google-beta
  machine_type = "e2-small"
  region       = "us-west1"
  tags         = ["http-server"]

  network_interface {
    network    = google_compute_network.default.id
    subnetwork = google_compute_subnetwork.subnet_a.id
    access_config {
      # add external ip to fetch packages
    }
  }
  disk {
    source_image = "debian-cloud/debian-11"
    auto_delete  = true
    boot         = true
  }

  # install nginx and serve a simple web page
  metadata = {
    startup-script = <<-EOF1
      #! /bin/bash
      set -euo pipefail

      export DEBIAN_FRONTEND=noninteractive
      apt-get update
      apt-get install -y nginx-light jq

      NAME=$(curl -H "Metadata-Flavor: Google" "http://metadata.google.internal/computeMetadata/v1/instance/hostname")
      IP=$(curl -H "Metadata-Flavor: Google" "http://metadata.google.internal/computeMetadata/v1/instance/network-interfaces/0/ip")
      METADATA=$(curl -f -H "Metadata-Flavor: Google" "http://metadata.google.internal/computeMetadata/v1/instance/attributes/?recursive=True" | jq 'del(.["startup-script"])')

      cat <<EOF > /var/www/html/index.html
      <pre>
      Name: $NAME
      IP: $IP
      Metadata: $METADATA
      </pre>
      EOF
    EOF1
  }
  lifecycle {
    create_before_destroy = true
  }
}
resource "google_compute_instance_template" "instance_template_b" {
  name         = "gil7-backendeast1-template"
  provider     = google-beta
  machine_type = "e2-small"
  region       = "us-east1"
  tags         = ["http-server"]

  network_interface {
    network    = google_compute_network.default.id
    subnetwork = google_compute_subnetwork.subnet_b.id
    access_config {
      # add external ip to fetch packages
    }
  }
  disk {
    source_image = "debian-cloud/debian-11"
    auto_delete  = true
    boot         = true
  }

  # install nginx and serve a simple web page
  metadata = {
    startup-script = <<-EOF1
      #! /bin/bash
      set -euo pipefail

      export DEBIAN_FRONTEND=noninteractive
      apt-get update
      apt-get install -y nginx-light jq

      NAME=$(curl -H "Metadata-Flavor: Google" "http://metadata.google.internal/computeMetadata/v1/instance/hostname")
      IP=$(curl -H "Metadata-Flavor: Google" "http://metadata.google.internal/computeMetadata/v1/instance/network-interfaces/0/ip")
      METADATA=$(curl -f -H "Metadata-Flavor: Google" "http://metadata.google.internal/computeMetadata/v1/instance/attributes/?recursive=True" | jq 'del(.["startup-script"])')

      cat <<EOF > /var/www/html/index.html
      <pre>
      Name: $NAME
      IP: $IP
      Metadata: $METADATA
      </pre>
      EOF
    EOF1
  }
  lifecycle {
    create_before_destroy = true
  }
}

如要建立代管執行個體群組,請使用 google_compute_instance_group_manager 資源

resource "google_compute_region_instance_group_manager" "mig_a" {
  name     = "gl7-ilb-miga"
  provider = google-beta
  region   = "us-west1"
  version {
    instance_template = google_compute_instance_template.instance_template_a.id
    name              = "primary"
  }
  base_instance_name = "vm"
  target_size        = 2
}
resource "google_compute_region_instance_group_manager" "mig_b" {
  name     = "gl7-ilb-migb"
  provider = google-beta
  region   = "us-east1"
  version {
    instance_template = google_compute_instance_template.instance_template_b.id
    name              = "primary"
  }
  base_instance_name = "vm"
  target_size        = 2
}

API

使用 instanceTemplates.insert 方法建立執行個體範本,並將 PROJECT_ID 替換為您的專案 ID。

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/instanceTemplates

{
  "name":"gil7-backendwest1-template",
  "properties":{
     "machineType":"e2-standard-2",
     "tags":{
       "items":[
         "allow-ssh",
         "load-balanced-backend"
       ]
     },
     "metadata":{
        "kind":"compute#metadata",
        "items":[
          {
            "key":"startup-script",
            "value":"#! /bin/bash\napt-get update\napt-get install
            apache2 -y\na2ensite default-ssl\na2enmod ssl\n
            vm_hostname=\"$(curl -H \"Metadata-Flavor:Google\"
            \\\nhttp://169.254.169.254/computeMetadata/v1/instance/name)\"\n
            echo \"Page served from: $vm_hostname\" | \\\ntee
            /var/www/html/index.html\nsystemctl restart apache2"
          }
        ]
     },
     "networkInterfaces":[
       {
         "network":"projects/PROJECT_ID/global/networks/NETWORK",
         "subnetwork":"regions/REGION_A/subnetworks/SUBNET_A",
         "accessConfigs":[
           {
             "type":"ONE_TO_ONE_NAT"
           }
         ]
       }
     ],
     "disks":[
       {
         "index":0,
         "boot":true,
         "initializeParams":{
           "sourceImage":"projects/debian-cloud/global/images/family/debian-12"
         },
         "autoDelete":true
       }
     ]
  }
}

使用 instanceGroupManagers.insert 方法,在每個區域中建立受管理的執行個體群組,並將 PROJECT_ID 替換為您的專案 ID。

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/{zone}/instanceGroupManagers

{
  "name": "gl7-ilb-mig-a",
  "zone": "projects/PROJECT_ID/zones/ZONE_A",
  "instanceTemplate": "projects/PROJECT_ID/global/instanceTemplates/gil7-backendwest1-template",
  "baseInstanceName": "gl7-ilb-mig-b",
  "targetSize": 2
}
POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/instanceTemplates

{
  "name":"gil7-backendeast1-template",
  "properties":{
     "machineType":"e2-standard-2",
     "tags":{
       "items":[
         "allow-ssh",
         "load-balanced-backend"
       ]
     },
     "metadata":{
        "kind":"compute#metadata",
        "items":[
          {
            "key":"startup-script",
            "value":"#! /bin/bash\napt-get update\napt-get install
            apache2 -y\na2ensite default-ssl\na2enmod ssl\n
            vm_hostname=\"$(curl -H \"Metadata-Flavor:Google\"
            \\\nhttp://169.254.169.254/computeMetadata/v1/instance/name)\"\n
            echo \"Page served from: $vm_hostname\" | \\\ntee
            /var/www/html/index.html\nsystemctl restart apache2"
          }
        ]
     },
     "networkInterfaces":[
       {
         "network":"projects/PROJECT_ID/global/networks/NETWORK",
         "subnetwork":"regions/REGION_B/subnetworks/SUBNET_B",
         "accessConfigs":[
           {
             "type":"ONE_TO_ONE_NAT"
           }
         ]
       }
     ],
     "disks":[
       {
         "index":0,
         "boot":true,
         "initializeParams":{
           "sourceImage":"projects/debian-cloud/global/images/family/debian-12"
         },
         "autoDelete":true
       }
     ]
  }
}

使用 instanceGroupManagers.insert 方法,在每個區域中建立受管理的執行個體群組,並將 PROJECT_ID 替換為您的專案 ID。

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/{zone}/instanceGroupManagers

{
  "name": "gl7-ilb-mig-b",
  "zone": "projects/PROJECT_ID/zones/ZONE_B",
  "instanceTemplate": "projects/PROJECT_ID/global/instanceTemplates/gil7-backendwest1-template",
  "baseInstanceName": "gl7-ilb-mig-b",
  "targetSize": 2
}

設定負載平衡器

本範例說明如何建立下列跨區域內部應用程式負載平衡器資源:

  • 通用 HTTP 健康狀態檢查。
  • 全球後端服務,其中代管執行個體群組做為後端。
  • 網址對應。請務必參照目標 HTTP(S) Proxy 的全域網址對應。全域網址對應會根據您為傳入網址的主機和路徑定義的規則,將要求轉送至全域後端服務。通用目標 Proxy 規則可以參照通用網址對應。
  • 全域 SSL 憑證 (適用於 HTTPS)。
  • 全球目標 Proxy。
  • 兩個含有區域 IP 位址的全域轉送規則。針對轉送規則的 IP 位址,請使用 SUBNET_ASUBNET_B IP 位址範圍。如果您嘗試使用僅限 Proxy 的子網路,轉送規則建立作業將會失敗。

主控台

開始設定

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

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

  2. 點選「建立負載平衡器」
  3. 在「Type of load balancer」(負載平衡器類型)部分,選取「Application Load Balancer (HTTP/HTTPS)」(應用程式負載平衡器 (HTTP/HTTPS)),然後點選「Next」(下一步)
  4. 在「公開或內部」部分,選取「內部」,然後點選「下一步」
  5. 在「跨區域或單一區域部署」部分,選取「最適合跨區域工作負載」,然後點選「下一步」
  6. 按一下 [設定]

基本設定

  1. 提供負載平衡器的「名稱」
  2. 在「Network」(網路) 中選取 NETWORK

使用兩個轉送規則設定前端

HTTP:

  1. 按一下「前端設定」
    1. 提供轉送規則的「Name」(名稱)
    2. 在「子網路區域」清單中選取「REGION_A」。

      保留僅限 Proxy 的子網路

    3. 在「Subnetwork」(子網路) 清單中選取「SUBNET_A」。
    4. 在「IP address」清單中,按一下「Create IP address」。系統會開啟「保留靜態內部 IP 位址」頁面。
      • 為靜態 IP 位址提供「名稱」
      • 在「Static IP address」清單中,選取「Let me choose」
      • 在「Custom IP address」(自訂 IP 位址) 欄位中輸入 10.1.2.99
      • 選取「預訂」
  2. 按一下 [完成]
  3. 如要新增第二個轉寄規則,請按一下「新增前端 IP 和通訊埠」
    1. 提供轉送規則的「Name」(名稱)
    2. 在「子網路區域」清單中選取「REGION_B」。

      保留僅限 Proxy 的子網路

    3. 在「Subnetwork」(子網路) 清單中選取「SUBNET_B」。
    4. 在「IP address」清單中,按一下「Create IP address」。系統會開啟「保留靜態內部 IP 位址」頁面。
      • 為靜態 IP 位址提供「名稱」
      • 在「Static IP address」清單中,選取「Let me choose」
      • 在「Custom IP address」(自訂 IP 位址) 欄位中輸入 10.1.3.99
      • 選取「預訂」
  4. 按一下 [完成]

針對 HTTPS:

如果您在用戶端與負載平衡器間使用的是 HTTPS,則需要有一個或多個 SSL 憑證資源才能設定 Proxy。如要建立 all-regions Google 代管憑證,請參閱下列說明文件:

建立 Google 代管憑證後,請 將憑證直接附加至目標 Proxy。跨區域內部應用程式負載平衡器不支援憑證對應項目。

如要建立 all-regions 自行管理憑證,請參閱以下說明文件: 部署區域性自行管理憑證

  1. 按一下「前端設定」
    1. 提供轉送規則的「Name」(名稱)
    2. 在「Protocol」欄位中選取 HTTPS (includes HTTP/2)
    3. 確認「Port」(通訊埠) 已設為 443
    4. 在「子網路區域」清單中選取「REGION_A」。

      保留僅限 Proxy 的子網路

    5. 在「Subnetwork」(子網路) 清單中選取「SUBNET_A」。
    6. 在「IP address」清單中,按一下「Create IP address」。系統會開啟「保留靜態內部 IP 位址」頁面。
      • 為靜態 IP 位址提供「名稱」
      • 在「Static IP address」清單中,選取「Let me choose」
      • 在「Custom IP address」(自訂 IP 位址) 欄位中輸入 10.1.3.99
      • 選取「預訂」
    7. 在「新增憑證」部分中,選取憑證。
    8. 選用:如要新增主要 SSL 憑證以外的憑證,請按照下列指示操作:
      1. 按一下「新增憑證」
      2. 從清單中選取憑證。
    9. 從「SSL policy」清單中選取 SSL 政策。如果您尚未建立任何 SSL 政策,系統會套用預設 Google Cloud SSL 政策
    10. 按一下 [完成]

    新增第二個前端設定:

    1. 為前端設定提供名稱
    2. 在「Protocol」欄位中選取 HTTPS (includes HTTP/2)
    3. 確認「Port」(通訊埠) 已設為 443
    4. 在「子網路區域」清單中選取「REGION_B」。

      保留僅限 Proxy 的子網路

    5. 在「Subnetwork」(子網路) 清單中選取「SUBNET_B」。
    6. 在「IP address」清單中,按一下「Create IP address」。系統會開啟「保留靜態內部 IP 位址」頁面。
      • 為靜態 IP 位址提供「名稱」
      • 在「Static IP address」清單中,選取「Let me choose」
      • 在「Custom IP address」(自訂 IP 位址) 欄位中輸入 10.1.3.99
      • 選取「預訂」
    7. 在「新增憑證」部分中,選取憑證。
    8. 選用:如要新增主要 SSL 憑證以外的憑證,請按照下列指示操作:
      1. 按一下「新增憑證」
      2. 從清單中選取憑證。
    9. 從「SSL policy」清單中選取 SSL 政策。如果您尚未建立任何 SSL 政策,系統會套用預設 Google Cloud SSL 政策
    10. 按一下 [完成]
    設定後端服務
    1. 按一下「後端設定」
    2. 在「Create or select backend services」清單中,按一下「Create a backend service」
    3. 為後端服務提供「Name」(名稱)
    4. 在「通訊協定」部分選取「HTTP」
    5. 在「Named Port」(已命名的通訊埠) 中輸入 http
    6. 在「Backend type」清單中,選取「Instance group」
    7. 在「New backend」專區中:
      • 在「Instance group」清單中,選取 REGION_A 中的 gl4-ilb-miga
      • 將「Port numbers」(通訊埠編號) 設為 80
      • 按一下 [完成]
      • 如要新增其他後端,請按一下「新增後端」
      • 在「Instance group」清單中,選取 REGION_B 中的 gl4-ilb-migb
      • 將「Port numbers」(通訊埠編號) 設為 80
      • 按一下 [完成]
    8. 在「健康狀態檢查」清單中,按一下「建立健康狀態檢查」
      • 在「Name」(名稱) 欄位中輸入 global-http-health-check
      • 將「Protocol」(通訊協定) 設為 HTTP
      • 將「Port」(通訊埠) 設為 80
      • 按一下 [儲存]

    設定轉送規則

    1. 按一下「轉送規則」
    2. 在「Mode」中,選取「Simple host and path rule」
    3. 確認任何不相符主機和路徑都只有一個後端服務。

    檢查設定

    1. 按一下「檢查並完成」
    2. 查看負載平衡器設定。
    3. 按一下 [建立]。

gcloud

  1. 使用 gcloud compute health-checks create http 指令定義 HTTP 健康狀態檢查。

    gcloud compute health-checks create http global-http-health-check \
       --use-serving-port \
       --global
    
  2. 使用 gcloud compute backend-services create 指令定義後端服務。

    gcloud compute backend-services create BACKEND_SERVICE_NAME \
      --load-balancing-scheme=INTERNAL_MANAGED \
      --protocol=HTTP \
      --enable-logging \
      --logging-sample-rate=1.0 \
      --health-checks=global-http-health-check \
      --global-health-checks \
      --global
    
  3. 使用 gcloud compute backend-services add-backend 指令,將後端新增到後端服務。

    gcloud compute backend-services add-backend BACKEND_SERVICE_NAME \
      --balancing-mode=UTILIZATION \
      --instance-group=gl7-ilb-mig-a \
      --instance-group-zone=ZONE_A \
      --global
    
    gcloud compute backend-services add-backend BACKEND_SERVICE_NAME \
      --balancing-mode=UTILIZATION \
      --instance-group=gl7-ilb-mig-b \
      --instance-group-zone=ZONE_B \
      --global
    
  4. 使用 gcloud compute url-maps create 指令建立網址對應。

    gcloud compute url-maps create gl7-gilb-url-map \
      --default-service=BACKEND_SERVICE_NAME \
      --global
    
  5. 建立目標 Proxy。

    HTTP:

    使用 gcloud compute target-http-proxies create 指令建立目標 Proxy。

    gcloud compute target-http-proxies create gil7-http-proxy \
      --url-map=gl7-gilb-url-map \
      --global
    

    適用於 HTTPS:

    如要建立 Google 代管的憑證,請參閱下列說明文件:

    建立 Google 代管憑證後,請直接將憑證附加至目標 Proxy。跨區域內部應用程式負載平衡器不支援憑證對應項目。

    如要建立自行管理的憑證,請參閱下列說明文件:

    將檔案路徑指派給變數名稱。

    export LB_CERT=PATH_TO_PEM_FORMATTED_FILE
    
    export LB_PRIVATE_KEY=PATH_TO_LB_PRIVATE_KEY_FILE
    

    使用 gcloud beta certificate-manager certificates create 指令建立全區域 SSL 憑證。

    gcloud certificate-manager certificates create gilb-certificate \
      --private-key-file=$LB_PRIVATE_KEY \
      --certificate-file=$LB_CERT \
      --scope=all-regions
    

    使用 SSL 憑證,透過 gcloud compute target-https-proxies create 指令建立目標 Proxy

    gcloud compute target-https-proxies create gil7-https-proxy \
      --url-map=gl7-gilb-url-map \
      --certificate-manager-certificates=gilb-certificate \
      --global
    
  6. 建立兩個轉送規則,一個在 REGION_B 區域中使用 VIP (10.1.2.99),另一個在 REGION_A 區域中使用 VIP (10.1.3.99)。詳情請參閱「預留靜態內部 IPv4 位址」。

    如果是自訂網路,您必須參照轉送規則中的子網路。請注意,這是 VM 子網路,而不是 Proxy 子網路。

    HTTP:

    使用 gcloud compute forwarding-rules create 指令,並加上正確的旗標。

    gcloud compute forwarding-rules create FWRULE_A \
      --load-balancing-scheme=INTERNAL_MANAGED \
      --network=NETWORK \
      --subnet=SUBNET_A \
      --subnet-region=REGION_A \
      --address=10.1.2.99 \
      --ports=80 \
      --target-http-proxy=gil7-http-proxy \
      --global
    
    gcloud compute forwarding-rules create FWRULE_B \
      --load-balancing-scheme=INTERNAL_MANAGED \
      --network=NETWORK \
      --subnet=SUBNET_B \
      --subnet-region=REGION_B \
      --address=10.1.3.99 \
      --ports=80 \
      --target-http-proxy=gil7-http-proxy \
      --global
    

    適用於 HTTPS:

    使用 gcloud compute forwarding-rules create 指令,並加上正確的旗標。

    gcloud compute forwarding-rules create FWRULE_A \
      --load-balancing-scheme=INTERNAL_MANAGED \
      --network=NETWORK \
      --subnet=SUBNET_A \
      --subnet-region=REGION_A \
      --address=10.1.2.99 \
      --ports=443 \
      --target-https-proxy=gil7-https-proxy \
      --global
    
    gcloud compute forwarding-rules create FWRULE_B \
      --load-balancing-scheme=INTERNAL_MANAGED \
      --network=NETWORK \
      --subnet=SUBNET_B \
      --subnet-region=REGION_B \
      --address=10.1.3.99 \
      --ports=443 \
      --target-https-proxy=gil7-https-proxy \
      --global
    

Terraform

如要建立健康狀態檢查,請使用 google_compute_health_check 資源

resource "google_compute_health_check" "default" {
  provider = google-beta
  name     = "global-http-health-check"
  http_health_check {
    port_specification = "USE_SERVING_PORT"
  }
}

如要建立後端服務,請使用 google_compute_backend_service 資源

resource "google_compute_backend_service" "default" {
  name                  = "gl7-gilb-backend-service"
  provider              = google-beta
  protocol              = "HTTP"
  load_balancing_scheme = "INTERNAL_MANAGED"
  timeout_sec           = 10
  health_checks         = [google_compute_health_check.default.id]
  backend {
    group           = google_compute_region_instance_group_manager.mig_a.instance_group
    balancing_mode  = "UTILIZATION"
    capacity_scaler = 1.0
  }
  backend {
    group           = google_compute_region_instance_group_manager.mig_b.instance_group
    balancing_mode  = "UTILIZATION"
    capacity_scaler = 1.0
  }
}

如要建立網址對應,請使用 google_compute_url_map 資源

resource "google_compute_url_map" "default" {
  name            = "gl7-gilb-url-map"
  provider        = google-beta
  default_service = google_compute_backend_service.default.id
}

如要建立目標 HTTP Proxy,請使用 google_compute_target_http_proxy 資源

resource "google_compute_target_http_proxy" "default" {
  name     = "gil7target-http-proxy"
  provider = google-beta
  url_map  = google_compute_url_map.default.id
}

如要建立轉送規則,請使用 google_compute_forwarding_rule 資源

resource "google_compute_global_forwarding_rule" "fwd_rule_a" {
  provider              = google-beta
  depends_on            = [google_compute_subnetwork.proxy_subnet_a]
  ip_address            = "10.1.2.99"
  ip_protocol           = "TCP"
  load_balancing_scheme = "INTERNAL_MANAGED"
  name                  = "gil7forwarding-rule-a"
  network               = google_compute_network.default.id
  port_range            = "80"
  target                = google_compute_target_http_proxy.default.id
  subnetwork            = google_compute_subnetwork.subnet_a.id
}
resource "google_compute_global_forwarding_rule" "fwd_rule_b" {
  provider              = google-beta
  depends_on            = [google_compute_subnetwork.proxy_subnet_b]
  ip_address            = "10.1.3.99"
  ip_protocol           = "TCP"
  load_balancing_scheme = "INTERNAL_MANAGED"
  name                  = "gil7forwarding-rule-b"
  network               = google_compute_network.default.id
  port_range            = "80"
  target                = google_compute_target_http_proxy.default.id
  subnetwork            = google_compute_subnetwork.subnet_b.id
}

如要瞭解如何套用或移除 Terraform 設定,請參閱「基本 Terraform 指令」。

API

請向 healthChecks.insert 方法提出 POST 要求,並將 PROJECT_ID 替換為您的專案 ID,藉此建立健康狀態檢查。

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/healthChecks

{
"name": "global-http-health-check",
"type": "HTTP",
"httpHealthCheck": {
  "portSpecification": "USE_SERVING_PORT"
}
}

請對 backendServices.insert 方法提出 POST 要求,並將 PROJECT_ID 替換為您的專案 ID,藉此建立全域後端服務。

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/backendServices

{
"name": "BACKEND_SERVICE_NAME",
"backends": [
  {
    "group": "projects/PROJECT_ID/zones/ZONE_A/instanceGroups/gl7-ilb-mig-a",
    "balancingMode": "UTILIZATION"
  },
  {
    "group": "projects/PROJECT_ID/zones/ZONE_B/instanceGroups/gl7-ilb-mig-b",
    "balancingMode": "UTILIZATION"
  }
],
"healthChecks": [
  "projects/PROJECT_ID/regions/global/healthChecks/global-http-health-check"
],
"loadBalancingScheme": "INTERNAL_MANAGED"
}

請向 urlMaps.insert 方法提出 POST 要求,並將 PROJECT_ID 替換為您的專案 ID,藉此建立網址對應。

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/urlMaps

{
"name": "l7-ilb-map",
"defaultService": "projects/PROJECT_ID/global/backendServices/BACKEND_SERVICE_NAME"
}

HTTP

請對 targetHttpProxies.insert 方法提出 POST 要求,並將 PROJECT_ID 替換為您的專案 ID,藉此建立目標 HTTP Proxy。

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/targetHttpProxy

{
"name": "l7-ilb-proxy",
"urlMap": "projects/PROJECT_ID/global/urlMaps/l7-ilb-map"
}

請對 forwardingRules.insert 方法提出 POST 要求,並將 PROJECT_ID 替換為您的專案 ID,藉此建立轉送規則。

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/forwardingRules

{
"name": "FWRULE_A",
"IPAddress": "10.1.2.99",
"IPProtocol": "TCP",
"portRange": "80-80",
"target": "projects/PROJECT_ID/global/targetHttpProxies/l7-ilb-proxy",
"loadBalancingScheme": "INTERNAL_MANAGED",
"subnetwork": "projects/PROJECT_ID/regions/REGION_A/subnetworks/SUBNET_A",
"network": "projects/PROJECT_ID/global/networks/NETWORK",
"networkTier": "PREMIUM"
}
POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/forwardingRules

{
"name": "gil7forwarding-rule-b",
"IPAddress": "10.1.3.99",
"IPProtocol": "TCP",
"portRange": "80-80",
"target": "projects/PROJECT_ID/global/targetHttpProxies/l7-ilb-proxy",
"loadBalancingScheme": "INTERNAL_MANAGED",
"subnetwork": "projects/PROJECT_ID/regions/REGION_B/subnetworks/SUBNET_B",
"network": "projects/PROJECT_ID/global/networks/NETWORK",
"networkTier": "PREMIUM"
}

適用於 HTTPS

讀取憑證和私密金鑰檔案,然後建立 SSL 憑證。以下範例說明如何使用 Python 執行這項操作。

from pathlib import Path
from pprint import pprint
from typing import Union

from googleapiclient import discovery


def create_regional_certificate(
    project_id: str,
    region: str,
    certificate_file: Union[str, Path],
    private_key_file: Union[str, Path],
    certificate_name: str,
    description: str = "Certificate created from a code sample.",
) -> dict:
    """
    Create a regional SSL self-signed certificate within your Google Cloud project.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
        region: name of the region you want to use.
        certificate_file: path to the file with the certificate you want to create in your project.
        private_key_file: path to the private key you used to sign the certificate with.
        certificate_name: name for the certificate once it's created in your project.
        description: description of the certificate.

        Returns:
        Dictionary with information about the new regional SSL self-signed certificate.
    """
    service = discovery.build("compute", "v1")

    # Read the cert into memory
    with open(certificate_file) as f:
        _temp_cert = f.read()

    # Read the private_key into memory
    with open(private_key_file) as f:
        _temp_key = f.read()

    # Now that the certificate and private key are in memory, you can create the
    # certificate resource
    ssl_certificate_body = {
        "name": certificate_name,
        "description": description,
        "certificate": _temp_cert,
        "privateKey": _temp_key,
    }
    request = service.regionSslCertificates().insert(
        project=project_id, region=region, body=ssl_certificate_body
    )
    response = request.execute()
    pprint(response)

    return response

請對 targetHttpsProxies.insert 方法提出 POST 要求,並將 PROJECT_ID 替換為您的專案 ID,藉此建立目標 HTTPS Proxy。

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/targetHttpsProxy

{
"name": "l7-ilb-proxy",
"urlMap": "projects/PROJECT_ID/global/urlMaps/l7-ilb-map",
"sslCertificates": /projects/PROJECT_ID/global/sslCertificates/SSL_CERT_NAME
}

請對 globalForwardingRules.insert 方法提出 POST 要求,並將 PROJECT_ID 替換為您的專案 ID,藉此建立轉送規則。

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/forwardingRules

{
"name": "FWRULE_A",
"IPAddress": "10.1.2.99",
"IPProtocol": "TCP",
"portRange": "80-80",
"target": "projects/PROJECT_ID/global/targetHttpsProxies/l7-ilb-proxy",
"loadBalancingScheme": "INTERNAL_MANAGED",
"subnetwork": "projects/PROJECT_ID/regions/REGION_A/subnetworks/SUBNET_A",
"network": "projects/PROJECT_ID/global/networks/NETWORK",
"networkTier": "PREMIUM"
}
POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/forwardingRules

{
"name": "FWRULE_B",
"IPAddress": "10.1.3.99",
"IPProtocol": "TCP",
"portRange": "80-80",
"target": "projects/PROJECT_ID/global/targetHttpsProxies/l7-ilb-proxy",
"loadBalancingScheme": "INTERNAL_MANAGED",
"subnetwork": "projects/PROJECT_ID/regions/REGION_B/subnetworks/SUBNET_B",
"network": "projects/PROJECT_ID/global/networks/NETWORK",
"networkTier": "PREMIUM"
}

測試負載平衡器

建立 VM 執行個體來測試連線能力

  1. 建立用戶端 VM:

    gcloud compute instances create l7-ilb-client-a \
        --image-family=debian-12 \
        --image-project=debian-cloud \
        --network=NETWORK \
        --subnet=SUBNET_A \
        --zone=ZONE_A \
        --tags=allow-ssh
    
    gcloud compute instances create l7-ilb-client-b \
        --image-family=debian-12 \
        --image-project=debian-cloud \
        --network=NETWORK \
        --subnet=SUBNET_B \
        --zone=ZONE_B \
        --tags=allow-ssh
    
  2. 使用 SSH 連線至每個用戶端執行個體。

    gcloud compute ssh l7-ilb-client-a --zone=ZONE_A
    
    gcloud compute ssh l7-ilb-client-b --zone=ZONE_B
    
  3. 驗證 IP 位址是否提供主機名稱

    • 確認用戶端 VM 可連上這兩個 IP 位址。這個指令會傳回處理要求的後端 VM 名稱:

      curl 10.1.2.99
      
      curl 10.1.3.99
      

      如要進行 HTTPS 測試,請將 curl 替換為下列指令:

      curl -k 'https://DOMAIN_NAME:443' --connect-to DOMAIN_NAME:443:10.1.2.99:443
      
      curl -k 'https://DOMAIN_NAME:443' --connect-to DOMAIN_NAME:443:10.1.3.99:443
      

      DOMAIN_NAME 替換為應用程式網域名稱,例如 test.example.com

      -k 標記會讓 curl 略過憑證驗證。

    • 選用:使用已設定的 DNS 記錄,解析離用戶端 VM 最近的 IP 位址。例如,DNS_NAME 可以是 service.example.com

      curl DNS_NAME
      

執行 100 個要求並確認它們可達到負載平衡

HTTP

  {
    RESULTS=
    for i in {1..100}
    do
        RESULTS="$RESULTS:$(curl --silent 10.1.2.99)"
    done
    echo ""
    echo " Results of load-balancing to 10.1.2.99: "
    echo "***"
    echo "$RESULTS" | tr ':' '\n' | grep -Ev "^$" | sort | uniq -c
    echo
  }
  

  {
    RESULTS=
    for i in {1..100}
    do
      RESULTS="$RESULTS:$(curl --silent 10.1.3.99)"
    done
    echo ""
    echo " Results of load-balancing to 10.1.3.99: "
    echo "***"
    echo "$RESULTS" | tr ':' '\n' | grep -Ev "^$" | sort | uniq -c
    echo
  }
  

適用於 HTTPS

在以下指令碼中,將 DOMAIN_NAME 替換為應用程式的網域名稱,例如 test.example.com

  {
    RESULTS=
    for i in {1..100}
    do
      RESULTS="$RESULTS:$(curl -k -s 'https://DOMAIN_NAME:443' --connect-to DOMAIN_NAME:443:10.1.2.99:443)"
    done
    echo ""
    echo " Results of load-balancing to 10.1.2.99: "
    echo "***"
    echo "$RESULTS" | tr ':' '\n' | grep -Ev "^$" | sort | uniq -c
    echo
  }
  

  {
    RESULTS=
    for i in {1..100}
    do
       RESULTS="$RESULTS:$(curl -k -s 'https://DOMAIN_NAME:443' --connect-to DOMAIN_NAME:443:10.1.3.99:443)"
    done
    echo ""
    echo " Results of load-balancing to 10.1.3.99: "
    echo "***"
    echo "$RESULTS" | tr ':' '\n' | grep -Ev "^$" | sort | uniq -c
    echo
  }
  

測試容錯移轉

  1. REGION_B 中的後端處於不健康狀態或無法存取時,請確認是否已將後端移轉至 REGION_A 區域。如要模擬備援,請從 REGION_B 中移除所有後端:

    gcloud compute backend-services remove-backend BACKEND_SERVICE_NAME \
       --balancing-mode=UTILIZATION \
       --instance-group=gl7-ilb-mig-b \
       --instance-group-zone=ZONE_B
    
  2. 使用 SSH 連線至 REGION_B 中的用戶端 VM。

    gcloud compute ssh l7-ilb-client-b \
       --zone=ZONE_B
    
  3. 將要求傳送至 REGION_B 區域中的負載平衡 IP 位址。指令輸出內容會顯示 REGION_A 中後端 VM 的回應。

    在下列指令碼中,將 DOMAIN_NAME 替換為應用程式網域名稱,例如 test.example.com

    {
    RESULTS=
    for i in {1..100}
    do
      RESULTS="$RESULTS:$(curl -k -s 'https://DOMAIN_NAME:443' --connect-to DOMAIN_NAME:443:10.1.3.99:443)"
    done
    echo "***"
    echo "*** Results of load-balancing to 10.1.3.99: "
    echo "***"
    echo "$RESULTS" | tr ':' '\n' | grep -Ev "^$" | sort | uniq -c
    echo
    }
    

額外設定選項

本節會延伸說明設定範例,並提供替代和其他設定選項。所有工作都是選填項目。您可以按任何順序執行這些工作。

啟用工作階段相依性

這些程序會說明如何更新範例區域內部應用程式負載平衡器或跨區域內部應用程式負載平衡器的後端服務,以便後端服務使用產生的 Cookie 相依性、標頭欄位相依性或 HTTP Cookie 相依性。

啟用產生的 Cookie 相依性後,負載平衡器會在第一個要求中發出 Cookie。對於每個具有相同 Cookie 的後續要求,負載平衡器會將要求導向相同的後端虛擬機器 (VM) 執行個體或端點。在這個範例中,Cookie 的名稱為 GCILB

啟用標頭欄位親和性後,負載平衡器會根據 --custom-request-header 標記中指定的 HTTP 標頭值,將要求轉送至網路端點群組 (NEG) 中的後端 VM 或端點。只有在負載平衡區域政策為 RING_HASHMAGLEV,且後端服務的一致雜湊指定 HTTP 標頭名稱時,標頭欄位相依性才會有效。

啟用 HTTP Cookie 相依性後,負載平衡器會根據 HTTP_COOKIE 標記中指定的 HTTP Cookie (使用選用的 --affinity-cookie-ttl 標記),將要求轉送至 NEG 中的後端 VM 或端點。如果用戶端未在 HTTP 要求中提供 Cookie,Proxy 會產生 Cookie,並透過 Set-Cookie 標頭傳回給用戶端。只有在負載平衡區域政策為 RING_HASHMAGLEV,且後端服務的一致雜湊指定 HTTP cookie 時,HTTP cookie 親和性才有效。

控制台

如要為後端服務啟用或變更工作階段相依性,請按照下列步驟操作:

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

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

  2. 點選「後端」
  3. 按一下「gil7-backend-service」 (您為本範例建立的後端服務名稱),然後按一下「Edit」
  4. 在「後端服務詳細資料」頁面中,按一下「進階設定」
  5. 在「工作階段相依性」下方,選取所需的工作階段相依性類型。
  6. 按一下「更新」

gcloud

使用下列 Google Cloud CLI 指令,將後端服務更新為不同類型的工作階段相依性:

    gcloud compute backend-services update gil7-backend-service \
        --session-affinity=[GENERATED_COOKIE | HEADER_FIELD | HTTP_COOKIE | CLIENT_IP] \
        --global
    

API

如要設定工作階段相依性,請對 backendServices/patch 方法提出 `PATCH` 要求。

    PATCH https://compute.googleapis.com/compute/v1/projects/[PROJECT_ID]/global/backendServices/gil7-backend-service
    {
    "sessionAffinity": ["GENERATED_COOKIE" | "HEADER_FIELD" | "HTTP_COOKIE" | "CLIENT_IP" ]
    }
    

限制哪些用戶端可以將流量傳送至負載平衡器

您可以在這些用戶端上設定輸出防火牆規則,限制用戶端連線至內部 Application Load Balancer 轉送規則 VIP。根據服務帳戶標記,在特定用戶端 VM 上設定這些防火牆規則。

您無法使用防火牆規則限制特定內部應用程式負載平衡器轉送規則 VIP 的傳入流量。位於與轉送規則 VIP 相同的 VPC 網路和區域中的任何用戶端,通常都能將流量傳送至轉送規則 VIP。

此外,所有後端要求都來自使用僅限 Proxy 的子網路範圍內 IP 位址的 Proxy。您無法根據用戶端使用的轉送規則 VIP 建立防火牆規則,以便允許或拒絕這些後端的入站流量。

以下列舉幾個範例,說明如何使用輸出防火牆規則,限制負載平衡器轉送規則 VIP 的流量。

主控台

如要識別用戶端 VM,請標記要限制的特定 VM。這些標記可用來將防火牆規則與標記的用戶端 VM 建立關聯。接著,請在下列步驟中將標記新增至 TARGET_TAG 欄位。

您可以使用單一防火牆規則或多個規則來設定這項功能。

單一輸出防火牆規則

您可以設定一個防火牆輸出規則,拒絕所有從標記用戶端 VM 傳出的流量,並將這些流量傳送至負載平衡器的 VIP。

  1. 在 Google Cloud 控制台中,前往「Firewall rules」(防火牆規則) 頁面。

    前往「防火牆規則」

  2. 按一下「Create firewall rule」,建立規則,拒絕標記用戶端 VM 的傳出流量,以便將流量傳送至負載平衡器的 VIP。

    • Name (名稱):fr-deny-access
    • Network (網路):lb-network
    • Priority (優先順序):100
    • 流量方向Egress
    • 「相符時執行的動作」「拒絕」
    • 目標指定的目標標記
    • 「Target tags」(目標標記)TARGET_TAG
    • Destination filter (目的地篩選器):IP ranges (IP 範圍)
    • 目的地 IP 範圍10.1.2.99
    • 通訊協定和通訊埠
      • 選擇「Specified protocols and ports」
      • 勾選「tcp」tcp核取方塊,然後輸入 80 做為「Port number」(通訊埠編號)。
  3. 按一下 [建立]。

多個輸出防火牆規則

更具擴充性的做法是設定兩個規則。這是預設的低優先順序規則,可限制所有用戶端存取負載平衡器的 VIP。第二個優先順序較高的規則,允許部分標記用戶端存取負載平衡器的 VIP。只有標記的 VM 可以存取 VIP。

  1. 在 Google Cloud 控制台中,前往「Firewall rules」(防火牆規則) 頁面。

    前往「防火牆規則」

  2. 按一下「Create firewall rule」,建立優先順序較低的規則,以便預設拒絕存取權限:

    • Name (名稱):fr-deny-all-access-low-priority
    • Network (網路):lb-network
    • Priority (優先順序):200
    • 流量方向Egress
    • 「相符時執行的動作」「拒絕」
    • 目標指定的目標標記
    • 「Target tags」(目標標記)TARGET_TAG
    • Destination filter (目的地篩選器):IP ranges (IP 範圍)
    • 目的地 IP 範圍10.1.2.99
    • 通訊協定和通訊埠
      • 選擇「Specified protocols and ports」
      • 勾選「TCP」核取方塊,然後輸入 80 做為「Port number」(通訊埠編號)。
  3. 按一下 [建立]。

  4. 按一下「Create firewall rule」(建立防火牆規則),建立優先順序較高的規則,允許來自特定標記執行個體的流量。

    • Name (名稱):fr-allow-some-access-high-priority
    • Network (網路):lb-network
    • Priority (優先順序):100
    • 流量方向Egress
    • 「Action on match」(相符時執行的動作)「Allow」(允許)
    • 目標指定的目標標記
    • 「Target tags」(目標標記)TARGET_TAG
    • Destination filter (目的地篩選器):IP ranges (IP 範圍)
    • 目的地 IP 範圍10.1.2.99
    • 通訊協定和通訊埠
      • 選擇「Specified protocols and ports」
      • 勾選「TCP」核取方塊,然後輸入 80 做為「Port number」(通訊埠編號)。
  5. 按一下 [建立]。

gcloud

如要識別用戶端 VM,請標記要限制的特定 VM。然後在這些步驟中將標籤新增至 TARGET_TAG 欄位。

您可以使用單一防火牆規則或多個規則來設定這項功能。

單一輸出防火牆規則

您可以設定一個防火牆輸出規則,拒絕所有從標記用戶端 VM 傳出的流量,並將這些流量傳送至負載平衡器的 VIP。

gcloud compute firewall-rules create fr-deny-access \
  --network=lb-network \
  --action=deny \
  --direction=egress \
  --rules=tcp \
  --priority=100 \
  --destination-ranges=10.1.2.99 \
  --target-tags=TARGET_TAG

多個輸出防火牆規則

更具擴充性的做法是設定兩個規則:預設的低優先順序規則,可限制所有用戶端存取負載平衡器的 VIP,以及第二個優先順序較高的規則,可允許標記的用戶端存取負載平衡器的 VIP。只有標記的 VM 可以存取 VIP。

  1. 建立優先順序較低的規則:

    gcloud compute firewall-rules create fr-deny-all-access-low-priority \
      --network=lb-network \
      --action=deny \
      --direction=egress \
      --rules=tcp \
      --priority=200 \
      --destination-ranges=10.1.2.99
    
  2. 建立優先順序較高的規則:

    gcloud compute firewall-rules create fr-allow-some-access-high-priority \
      --network=lb-network \
      --action=allow \
      --direction=egress \
      --rules=tcp \
      --priority=100 \
      --destination-ranges=10.1.2.99 \
      --target-tags=TARGET_TAG
    

如要使用服務帳戶 (而非標記) 控管存取權,請在建立防火牆規則時使用 --target-service-accounts 選項,而非 --target-tags 標記。

根據子網路調整內部應用程式負載平衡器後端的受限存取權

隨著轉送規則數量增加,維持個別防火牆規則或在現有規則中新增負載平衡 IP 位址 (如前一個章節所述) 就會變得相當不便。如要避免這種情況,您可以從保留的子網路中分配轉送規則 IP 位址。接著,您可以使用保留的子網路做為防火牆規則的目的地範圍,允許或封鎖標記執行個體或服務帳戶的流量。這樣一來,您就能有效控管一組轉送規則 VIP 的存取權,而不必維護個別 VIP 防火牆輸出規則。

以下是設定這項功能的大致步驟,假設您會個別建立所有其他必要的負載平衡器資源。

gcloud

  1. 建立地區子網路,用於為轉送規則分配負載平衡 IP 位址:

    gcloud compute networks subnets create l7-ilb-restricted-subnet \
      --network=lb-network \
      --region=us-west1 \
      --range=10.127.0.0/24
    
  2. 建立轉送規則,從子網路取得位址。以下範例使用前一個步驟建立的子網路中的 10.127.0.1 位址。

    gcloud compute forwarding-rules create l7-ilb-forwarding-rule-restricted \
      --load-balancing-scheme=INTERNAL_MANAGED \
      --network=lb-network \
      --subnet=l7-ilb-restricted-subnet \
      --address=10.127.0.1 \
      --ports=80 \
      --global \
      --target-http-proxy=gil7-http-proxy
    
  3. 建立防火牆規則,限制目的地為轉送規則子網路 (l7-ilb-restricted-subnet) 中的 IP 範圍的流量:

    gcloud compute firewall-rules create restrict-traffic-to-subnet \
      --network=lb-network \
      --action=deny \
      --direction=egress \
      --rules=tcp:80 \
      --priority=100 \
      --destination-ranges=10.127.0.0/24 \
      --target-tags=TARGET_TAG
    

在多個內部轉送規則之間使用相同的 IP 位址

如要讓多個內部轉送規則共用相同的內部 IP 位址,您必須保留 IP 位址,並將其 --purpose 旗標設為 SHARED_LOADBALANCER_VIP

gcloud

gcloud compute addresses create SHARED_IP_ADDRESS_NAME \
    --region=REGION \
    --subnet=SUBNET_NAME \
    --purpose=SHARED_LOADBALANCER_VIP
如果您需要將 HTTP 流量重新導向至 HTTPS,可以建立兩個使用共用 IP 位址的轉送規則。詳情請參閱「為內部應用程式負載平衡器設定 HTTP 至 HTTPS 重新導向」。

設定 DNS 轉送政策

如果您的用戶端位於多個區域,建議您使用這些區域中的 VIP,讓跨區域內部應用程式負載平衡器可供存取。這種多區域設定可盡量減少延遲時間和網路傳輸費用。此外,您還可以設定以 DNS 為基礎的全域負載平衡解決方案,以便在地區性服務中斷時提供復原能力。詳情請參閱「管理 DNS 轉送政策和健康狀態檢查」。

gcloud

如要建立 TTL 為 30 秒的 DNS 項目,請使用 gcloud dns record-sets create 指令

gcloud dns record-sets create DNS_ENTRY --ttl="30" \
  --type="A" --zone="service-zone" \
  --routing-policy-type="GEO" \
  --routing-policy-data="REGION_A=gil7-forwarding-rule-a@global;REGION_B=gil7-forwarding-rule-b@global" \
  --enable-health-checking

更改下列內容:

  • DNS_ENTRY:記錄組的 DNS 或網域名稱

    例如 service.example.com

  • REGION_AREGION_B:您設定負載平衡器的區域

API

ResourceRecordSets.create 方法發出 POST 要求,即可建立 DNS 記錄。將 PROJECT_ID 替換為您的專案 ID。

POST https://www.googleapis.com/dns/v1/projects/PROJECT_ID/managedZones/SERVICE_ZONE/rrsets
{
  "name": "DNS_ENTRY",
  "type": "A",
  "ttl": 30,
  "routingPolicy": {
    "geo": {
      "items": [
        {
          "location": "REGION_A",
          "healthCheckedTargets": {
            "internalLoadBalancers": [
              {
                "loadBalancerType": "globalL7ilb",
                "ipAddress": "IP_ADDRESS",
                "port": "80",
                "ipProtocol": "tcp",
                "networkUrl": "https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/networks/lb-network",
                "project": "PROJECT_ID"
              }
            ]
          }
        },
        {
          "location": "REGION_B",
          "healthCheckedTargets": {
            "internalLoadBalancers": [
              {
                "loadBalancerType": "globalL7ilb",
                "ipAddress": "IP_ADDRESS_B",
                "port": "80",
                "ipProtocol": "tcp",
                "networkUrl": "https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/networks/lb-network",
                "project": "PROJECT_ID"
              }
            ]
          }
        }
      ]
    }
  }
}

更新用戶端 HTTP 保持運作逾時時間

在先前步驟中建立的負載平衡器已設定 用戶端 HTTP keepalive 逾時 的預設值。

如要更新用戶端 HTTP keepalive 逾時值,請按照下列操作說明操作。

控制台

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

    前往「負載平衡」

  2. 按一下要修改的負載平衡器名稱。
  3. 按一下「編輯」圖示
  4. 按一下「前端設定」
  5. 展開「進階功能」。在「HTTP 保持運作逾時」中,輸入逾時值。
  6. 按一下「更新」
  7. 如要查看變更內容,請依序按一下「Review and finalize」和「Update」

gcloud

針對 HTTP 負載平衡器,請使用 gcloud compute target-http-proxies update 指令更新目標 HTTP Proxy:

    gcloud compute target-http-proxies update TARGET_HTTP_PROXY_NAME \
        --http-keep-alive-timeout-sec=HTTP_KEEP_ALIVE_TIMEOUT_SEC \
        --global
    

針對 HTTPS 負載平衡器,請使用 gcloud compute target-https-proxies update 指令更新目標 HTTPS Proxy:

    gcloud compute target-https-proxies update TARGET_HTTPS_PROXY_NAME \
        --http-keep-alive-timeout-sec=HTTP_KEEP_ALIVE_TIMEOUT_SEC \
        --global
    

更改下列內容:

  • TARGET_HTTP_PROXY_NAME:目標 HTTP Proxy 的名稱。
  • TARGET_HTTPS_PROXY_NAME:目標 HTTPS Proxy 的名稱。
  • HTTP_KEEP_ALIVE_TIMEOUT_SEC:HTTP 保持運作逾時值,介於 5 到 600 秒。

啟用離群值偵測

您可以在全球後端服務上啟用異常值偵測功能,以便找出無伺服器 NEG 異常情形,並減少傳送至無伺服器 NEG 異常值的請求數量。

您可以使用下列其中一種方法,在後端服務中啟用異常值偵測功能:

  • consecutiveErrors 方法 (outlierDetection.consecutiveErrors),其中 5xx 系列 HTTP 狀態碼視為錯誤。
  • consecutiveGatewayFailure 方法 (outlierDetection.consecutiveGatewayFailure),其中只有 502503504 HTTP 狀態碼可視為錯誤。

請按照下列步驟,為現有後端服務啟用異常值偵測功能。請注意,即使啟用異常值偵測功能,某些要求仍可能會傳送至不健康的服務,並傳回 5xx 狀態碼給用戶端。如要進一步降低錯誤率,您可以為異常值偵測參數設定更積極的值。詳情請參閱 outlierDetection 欄位

主控台

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

    前往「負載平衡」

  2. 按一下您要編輯後端服務的負載平衡器名稱。

  3. 在「Load balancer details」(負載平衡器詳細資料) 頁面中,按一下 「Edit」(編輯)

  4. 在「Edit cross-region internal Application Load Balancer」(編輯跨區域內部應用程式負載平衡器) 頁面上,按一下「Backend configuration」(後端設定)

  5. 在「Backend configuration」(後端設定) 頁面上,針對要修改的後端服務,按一下 「Edit」(編輯)

  6. 向下捲動並展開「進階設定」部分。

  7. 在「異常值偵測」部分,勾選「啟用」核取方塊。

  8. 按一下 「Edit」 來設定異常值偵測功能。

    確認下列選項已設為指定的值:

    屬性
    連續錯誤 5
    間隔 1000
    基礎排除時間 30000
    排除百分比上限 50
    強制執行連續錯誤 100

    在本範例中,系統每秒執行一次異常值偵測分析。如果 Envoy Proxy 收到的連續 HTTP 5xx 狀態碼數量達到五個以上,後端端點就會從該 Envoy Proxy 的負載平衡集區中移除 30 秒。當強制百分比設為 100% 時,後端服務會在每次執行異常情況偵測分析時,強制從特定 Envoy Proxy 的負載平衡集區中,將不健康的端點彈出。如果符合排除條件,最多可從負載平衡集區中排除 50% 的後端端點。

  9. 按一下 [儲存]

  10. 如要更新後端服務,請按一下「更新」

  11. 如要更新負載平衡器,請在「Edit cross-region internal Application Load Balancer」(編輯跨區域內部應用程式負載平衡器) 頁面上,按一下「Update」(更新)

gcloud

  1. 將後端服務匯出為 YAML 檔案。

    gcloud compute backend-services export BACKEND_SERVICE_NAME \
      --destination=BACKEND_SERVICE_NAME.yaml --global
    

    BACKEND_SERVICE_NAME 替換為後端服務名稱。

  2. 編輯後端服務的 YAML 設定,新增異常值偵測欄位,如下列 YAML 設定中 outlierDetection 部分所示:

    在本範例中,系統每秒執行一次異常值偵測分析。如果 Envoy Proxy 收到的連續 HTTP 5xx 狀態碼數量達到五個以上,後端端點就會從該 Envoy Proxy 的負載平衡集區中移除 30 秒。當強制百分比設為 100% 時,後端服務會在每次執行異常情況偵測分析時,強制從特定 Envoy Proxy 的負載平衡集區中,將不健康的端點彈出。如果符合排除條件,最多可從負載平衡集區中排除 50% 的後端端點。

    name: BACKEND_SERVICE_NAME
    backends:
    - balancingMode: UTILIZATION
      capacityScaler: 1.0
      group: https://www.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION_A/networkEndpointGroups/SERVERLESS_NEG_NAME
    - balancingMode: UTILIZATION
      capacityScaler: 1.0
      group: https://www.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION_B/networkEndpointGroups/SERVERLESS_NEG_NAME_2
    outlierDetection:
      baseEjectionTime:
        nanos: 0
        seconds: 30
      consecutiveErrors: 5
      enforcingConsecutiveErrors: 100
      interval:
        nanos: 0
        seconds: 1
      maxEjectionPercent: 50
    port: 80
    selfLink: https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/backendServices/BACKEND_SERVICE_NAME
    sessionAffinity: NONE
    timeoutSec: 30
    ...
    

    更改下列內容:

    • BACKEND_SERVICE_NAME:後端服務名稱
    • PROJECT_ID:專案 ID
    • REGION_AREGION_B:負載平衡器已設定的區域。
    • SERVERLESS_NEG_NAME:第一個無伺服器 NEG 的名稱
    • SERVERLESS_NEG_NAME_2:第二個無伺服器 NEG 的名稱
  3. 匯入最新設定,更新後端服務。

    gcloud compute backend-services import BACKEND_SERVICE_NAME \
      --source=BACKEND_SERVICE_NAME.yaml --global
    

    後端服務現在已啟用離群值偵測功能。

後續步驟