使用 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 的子網路中,分配從負載平衡器傳送至服務後端之封包的來源位址。在本範例中,區域 REGION_A 的僅限 Proxy 子網路主要 IP 位址範圍為 10.129.0.0/23,而 REGION_B 的主要 IP 位址範圍為 10.130.0.0/23,這是建議的子網路大小。

  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 位址不得來自 --purpose 旗標設為 GLOBAL_MANAGED_PROXY 的保留僅限 Proxy 子網路。
    • 如要透過多個轉送規則使用相同的內部 IP 位址,請將 IP 位址 --purpose 標記設為 SHARED_LOADBALANCER_VIP
  7. 選用:設定 GEO 類型的 DNS 轉送政策,將用戶端流量轉送至最接近用戶端的地區中的負載平衡器 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 範圍。

虛擬私有雲中的任何區域都能存取跨區域內部應用程式負載平衡器。因此任何區域的用戶端都能從全球存取負載平衡器後端。

設定後端子網路

主控台

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

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

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

  3. 提供網路的「名稱」

  4. 在「Subnets」(子網路) 區段,將「Subnet creation mode」(子網路建立模式) 設為「Custom」(自訂)

  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

如要建立 VPC 網路,請使用 google_compute_network 資源

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

如要在 lb-network-crs-reg 網路中建立虛擬私有雲子網路,請使用 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 控制台,可以稍後在「Load balancing」(負載平衡) 頁面中建立僅限 Proxy 的子網路。

如要立即建立僅限 Proxy 的子網路,請按照下列步驟操作:

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

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

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

REGION_B 中建立僅限 Proxy 的子網路

  1. 在「子網路」分頁中,按一下「新增子網路」
  2. 提供僅限 Proxy 子網路的「名稱」
  3. 選取「區域」REGION_B
  4. 在「Purpose」(用途) 清單中,選取「Cross-region Managed Proxy」(跨區域受管理 Proxy)
  5. 在「IP address range」(IP 位址範圍) 欄位中,輸入 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 網路中建立 VPC 專屬 Proxy 的子網路,請使用 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 Cloud130.211.0.0/2235.191.0.0/16) 的所有 TCP 流量。這個範例會使用目標標記 load-balanced-backend 來辨識套用防火牆規則的 VM。

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

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

目標標記會定義後端執行個體。如果沒有目標標記,防火牆規則會套用至虛擬私有雲網路中的所有後端執行個體。建立後端 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」(相符時執行的動作)允許
    • 目標指定的目標標記
    • 「Target tags」(目標標記)allow-ssh
    • 來源篩選器IPv4 範圍
    • Source IPv4 ranges (來源 IPv4 範圍):0.0.0.0/0
    • 通訊協定和通訊埠
      • 選擇「指定的通訊協定與通訊埠」
      • 勾選「TCP」核取方塊,然後輸入 22 做為「Port number」(通訊埠編號)。
  3. 點選「建立」

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

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

      • 選擇「指定的通訊協定與通訊埠」
      • 勾選「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」(相符時執行的動作)允許
    • 目標指定的目標標記
    • 「Target tags」(目標標記)load-balanced-backend
    • 來源篩選器IPv4 範圍
    • Source IPv4 ranges (來源 IPv4 範圍):10.129.0.0/2310.130.0.0/23
    • 通訊協定和通訊埠
      • 選擇「指定的通訊協定與通訊埠」
      • 勾選「TCP」TCP核取方塊,然後輸入 80, 443, 8080 做為通訊埠編號。
  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 要求,建立 fw-ilb-to-backends 防火牆規則,並將 PROJECT_ID 替換為您的專案 ID。

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 要求,建立 fw-healthcheck 防火牆規則,並將 PROJECT_ID 替換為您的專案 ID。

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 防火牆規則,允許 firewalls.insert 方法的 Proxy 子網路內 TCP 流量,並將 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. 在「Cross-region or single region deployment」(跨區域或單一區域部署) 部分,選取「Best for cross-region workloads」(最適合跨區域工作負載),然後點選「Next」(下一步)
  6. 按一下 [設定]

基本設定

  1. 在「Name」(名稱) 中輸入負載平衡器的名稱。
  2. 在「Network」(網路) 中選取 NETWORK

設定前端,並使用兩項轉送規則

HTTP:

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

      保留僅限 Proxy 子網路

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

    設定轉送規則

    1. 按一下「轉送規則」
    2. 在「模式」中,選取「簡易型主機與路徑規則」
    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

提出 POST 要求,呼叫 healthChecks.insert 方法來建立健康狀態檢查,並將 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 要求,建立目標 HTTP Proxy,並將 PROJECT_ID 替換為您的專案 ID。

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 要求,建立目標 HTTPS Proxy,並將 PROJECT_ID 換成您的專案 ID。

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,將要求轉送至 NEG 中的後端 VM 或端點,並可選擇使用 --affinity-cookie-ttl 旗標。如果用戶端未在 HTTP 要求中提供 Cookie,Proxy 會產生 Cookie,並在 Set-Cookie 標頭中傳回給用戶端。只有在負載平衡區域政策為 RING_HASHMAGLEV,且後端服務的穩定雜湊指定 HTTP Cookie 時,HTTP Cookie 親和性才有效。

控制台

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

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

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

  2. 點選「後端」
  3. 按一下「gil7-backend-service」 (您為本範例建立的後端服務名稱),然後按一下「編輯」
  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" ]
    }
    

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

您可以在用戶端上設定輸出防火牆規則,限制用戶端連線至內部應用程式負載平衡器轉送規則 VIP。根據服務帳戶標記,在特定用戶端 VM 上設定這些防火牆規則。

您無法使用防火牆規則,限制傳入特定內部應用程式負載平衡器轉送規則 VIP 的流量。一般來說,只要用戶端位於與轉送規則 VIP 相同的虛擬私有雲網路和區域,就能將流量傳送至轉送規則 VIP。

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

以下是一些範例,說明如何使用輸出防火牆規則,將流量限制在負載平衡器的轉送規則 VIP。

主控台

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

您可以設定單一或多個防火牆規則。

單一輸出防火牆規則

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

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

    前往「防火牆規則」

  2. 按一下「建立防火牆規則」,建立規則來拒絕從已加上標記的用戶端 VM 到負載平衡器 VIP 的輸出流量。

    • Name (名稱):fr-deny-access
    • Network (網路):lb-network
    • Priority (優先順序):100
    • Direction of traffic (流量方向):「Egress」(輸出)
    • 「Action on match」(相符時執行的動作):選取「Deny」(拒絕)
    • 目標指定的目標標記
    • 「Target tags」(目標標記)TARGET_TAG
    • Destination filter (目的地篩選器):「IP ranges」(IP 範圍)
    • Destination IP ranges (目的地 IP 範圍):10.1.2.99
    • 通訊協定和通訊埠
      • 選擇「指定的通訊協定與通訊埠」
      • 勾選「tcp」tcp核取方塊,然後輸入 80 做為通訊埠編號。
  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
    • Direction of traffic (流量方向):「Egress」(輸出)
    • 「Action on match」(相符時執行的動作):選取「Deny」(拒絕)
    • 目標指定的目標標記
    • 「Target tags」(目標標記)TARGET_TAG
    • Destination filter (目的地篩選器):「IP ranges」(IP 範圍)
    • Destination IP ranges (目的地 IP 範圍):10.1.2.99
    • 通訊協定和通訊埠
      • 選擇「指定的通訊協定與通訊埠」
      • 勾選「TCP」核取方塊,然後輸入 80 做為「Port number」(通訊埠編號)。
  3. 點選「建立」

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

    • Name (名稱):fr-allow-some-access-high-priority
    • Network (網路):lb-network
    • Priority (優先順序):100
    • Direction of traffic (流量方向):「Egress」(輸出)
    • 「Action on match」(相符時執行的動作)允許
    • 目標指定的目標標記
    • 「Target tags」(目標標記)TARGET_TAG
    • Destination filter (目的地篩選器):「IP ranges」(IP 範圍)
    • Destination IP ranges (目的地 IP 範圍):10.1.2.99
    • 通訊協定和通訊埠
      • 選擇「指定的通訊協定與通訊埠」
      • 勾選「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 保持連線逾時的預設值。

如要更新用戶端 HTTP 保持連線逾時,請按照下列操作說明操作。

控制台

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

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

  2. 按一下要修改的負載平衡器名稱。
  3. 按一下「編輯」
  4. 按一下「前端設定」
  5. 展開「進階功能」。在「HTTP 保持運作逾時」部分, 輸入逾時值。
  6. 按一下「更新」
  7. 如要檢查變更,請依序按一下「檢查並完成」和「更新」

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」(負載平衡)頁面。

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

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

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

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

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

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

  7. 在「Outlier detection」(離群值偵測) 專區中,勾選「Enable」(啟用) 核取方塊。

  8. 按一下「編輯」,設定離群值偵測。

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

    屬性
    連續錯誤 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 設定,在 outlierDetection 區段中新增離群值偵測的欄位,如下列 YAML 設定中醒目顯示的部分:

    在本例中,離群值偵測分析每秒執行一次。如果 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
    

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

後續步驟