ACE-210:GCP 負載均衡深度解析——ALB、CDN 與 Cloud Armor 完全指南
前言
流量進到你的 GCP 系統,第一道門就是負載均衡器。流量怎麼分、SSL 在哪終止、要不要快取、怎麼擋攻擊,都是它在管。搞懂 GCP 的負載均衡架構,不只是 ACE 考試的核心考點,要設計高可用系統也少不了它。
這篇是 ACE 進階系列第 5 課,我們先從產品改名講起,再把整套 GCP 負載均衡體系過一遍。
命名更新(2024)
⚠️ 重要:Google 從 2023 年起陸續把負載均衡器改名,向業界標準看齊。考試兩套名稱都可能出現,新舊都得認得:
| 新名稱(2024+) | 舊名稱 | 層級 | 範圍 |
|---|---|---|---|
| Application Load Balancer (ALB) | HTTP(S) Load Balancer | L7 | Global / Regional |
| Network Load Balancer (NLB) | TCP Proxy / SSL Proxy LB | L4 | Global / Regional |
| Passthrough Network LB | External TCP/UDP Network LB | L4 | Regional |
| Internal Application LB | Internal HTTP(S) LB | L7 | Regional |
| Internal Network LB | Internal TCP/UDP LB | L4 | Regional |
GCP 負載均衡全景圖
外部流量
│
├── L7 (HTTP/HTTPS/gRPC)
│ ├── Global Application LB ← 全球 Anycast,CDN 整合
│ └── Regional Application LB ← 區域級,資料合規
│
└── L4 (TCP/UDP/SSL)
├── Network LB (Proxy) ← SSL/TCP proxy,全球/區域
└── Passthrough Network LB ← 直通,保留原始 IP
內部流量
├── Internal Application LB (L7) ← 微服務 L7 路由
└── Internal Network LB (L4) ← 服務內部 TCP/UDP
Application Load Balancer(ALB)
全球 vs 區域 ALB
| 特性 | Global ALB | Regional ALB |
|---|---|---|
| IP 類型 | Anycast 單一全球 IP | 區域 IP |
| 路由策略 | Google 骨幹網最佳路由 | 嚴格區域路由 |
| 後端範圍 | 跨區域後端 | 單一區域後端 |
| Cloud CDN | ✅ 支援 | ❌ 不支援 |
| Cloud Armor | ✅ 支援 | ✅ 支援 |
| 資料落地 | 可能跨區域 | 嚴格留在區域內 |
| 適合場景 | 全球用戶、高可用 | GDPR 合規、成本最佳化 |
2025 年最佳實踐:多數情況直接選 Global ALB 就對了。Google 的路由演算法現在更懂區域感知,效能跟合規之間平衡得比以前好。
ALB 元件架構
使用者請求
│
▼
[Forwarding Rule] ← 定義 IP + Port,是流量入口
│
▼
[Target Proxy] ← HTTP Proxy 或 HTTPS Proxy(處理 SSL)
│
▼
[URL Map] ← 路由規則(Host + Path 決定後端)
│
├── /api/* → [Backend Service A]
├── /cdn/* → [Backend Service B + Cloud CDN]
└── default → [Backend Service C]
│
▼
[Health Check] → 檢查後端健康
│
[Backend:MIG / NEG / Cloud Run]
建立 ALB 完整步驟
# 1. 建立健康檢查
gcloud compute health-checks create http my-health-check \
--port=8080 \
--request-path=/health \
--check-interval=10s \
--timeout=5s \
--unhealthy-threshold=2 \
--healthy-threshold=1
# 2. 建立後端服務
gcloud compute backend-services create my-backend \
--protocol=HTTP \
--port-name=http \
--health-checks=my-health-check \
--global
# 3. 加入後端(Managed Instance Group)
gcloud compute backend-services add-backend my-backend \
--instance-group=my-mig \
--instance-group-zone=asia-east1-b \
--global
# 4. 建立 URL Map(路由規則)
gcloud compute url-maps create my-url-map \
--default-service=my-backend
# 5. 建立 Target HTTPS Proxy
gcloud compute target-https-proxies create my-https-proxy \
--url-map=my-url-map \
--ssl-certificates=my-ssl-cert
# 6. 建立 Forwarding Rule(流量入口)
gcloud compute forwarding-rules create my-forwarding-rule \
--global \
--target-https-proxy=my-https-proxy \
--ports=443
URL Map:路由規則詳解
URL Map 是 ALB 的核心路由邏輯,可以從三個維度做路由:
Path 路由(按路徑)
# 建立含路徑規則的 URL Map
gcloud compute url-maps create my-url-map \
--default-service=default-backend
# 新增路徑規則
gcloud compute url-maps add-path-rule my-url-map \
--service=api-backend \
--path-matcher-name=api-matcher \
--new-hosts=example.com \
--paths="/api/*"
gcloud compute url-maps add-path-rule my-url-map \
--service=static-backend \
--path-matcher-name=static-matcher \
--paths="/static/*,/images/*"
example.com/api/users → api-backend
example.com/static/js/* → static-backend(可加 CDN)
example.com/* → default-backend
Host 路由(按域名)
# api.example.com → API 後端,www.example.com → Web 後端
gcloud compute url-maps add-host-rule my-url-map \
--hosts=api.example.com \
--path-matcher-name=api-matcher
Header 路由(按 Header,2023+)
# YAML 配置範例(適用 A/B 測試)
headerAction:
requestHeadersToAdd:
- headerName: X-Backend
headerValue: canary
routeRules:
- matchRules:
- headers:
- headerName: User-Agent
regexMatch: .*Mobile.*
service: mobile-backend
後端類型:Instance Groups vs NEGs
Managed Instance Group(MIG)— 最常見
# 建立 Instance Template
gcloud compute instance-templates create web-template \
--machine-type=e2-medium \
--image-family=debian-12 \
--image-project=debian-cloud \
--tags=http-server
# 建立 MIG
gcloud compute instance-groups managed create my-mig \
--template=web-template \
--size=2 \
--zone=asia-east1-b
# 設定 Named Port(讓 LB 知道流量走哪個 Port)
gcloud compute instance-groups set-named-ports my-mig \
--named-ports=http:8080 \
--zone=asia-east1-b
MIG vs Unmanaged IG:
| 特性 | MIG(托管) | Unmanaged IG |
|---|---|---|
| 自動修復(Auto-healing) | ✅ | ❌ |
| 自動擴縮(Autoscaling) | ✅ | ❌ |
| 滾動更新 | ✅ | 手動 |
| 建議用途 | 生產環境 | 遺留系統、測試 |
ACE 考試:有 Autoscaling 需求 → 一定選 MIG
Network Endpoint Groups(NEGs)
NEG 讓負載均衡器可以直接路由到 IP:Port 這一層,用起來更有彈性:
| NEG 類型 | 適用後端 | 說明 |
|---|---|---|
| Zonal NEG | Compute Engine VM | 細緻的 IP+Port 層級後端 |
| Internet NEG | 外部 IP 端點 | 對外部服務(on-prem、第三方 API)做 LB |
| Serverless NEG | Cloud Run / App Engine / Cloud Functions | 無伺服器後端的 LB 入口 |
| Private Service Connect NEG | 合作夥伴服務 | 私有存取 Datadog、Splunk 等 |
| Hybrid Connectivity NEG | 地端資源(via Cloud Interconnect) | 混合雲整合 |
Serverless NEG — Cloud Run + ALB 整合
這套架構,2025 年的考試越來越常出:
# 1. 建立 Serverless NEG(指向 Cloud Run 服務)
gcloud compute network-endpoint-groups create my-run-neg \
--region=asia-east1 \
--network-endpoint-type=serverless \
--cloud-run-service=my-service
# 2. 建立後端服務
gcloud compute backend-services create run-backend \
--global \
--load-balancing-scheme=EXTERNAL_MANAGED
# 3. 加入 Serverless NEG
gcloud compute backend-services add-backend run-backend \
--global \
--network-endpoint-group=my-run-neg \
--network-endpoint-group-region=asia-east1
好處:Cloud Run 接上 ALB 之後,就能多拿到這些:
- 自訂網域 + Google 管理 SSL 憑證
- Cloud CDN 快取靜態資源
- Cloud Armor WAF 防護
SSL/TLS 與 Certificate Manager
Google 管理憑證(自動續期)
# 建立 Google 管理的 SSL 憑證
gcloud compute ssl-certificates create my-cert \
--domains=www.example.com,api.example.com \
--global
憑證由 Google 託管的 CA 自動簽發,效期 90 天,到期前約一個月會自動續期。
Certificate Manager(推薦,2025 最佳實踐)
Certificate Manager 把憑證管理收在同一個介面,能應付比較複雜的場景:
# 建立 DNS 授權(用於 wildcard 憑證)
gcloud certificate-manager dns-authorizations create my-dns-auth \
--domain="example.com"
# 建立憑證(Certificate Manager 管理)
gcloud certificate-manager certificates create my-cert \
--domains="example.com,*.example.com" \
--dns-authorizations=my-dns-auth
# 建立 Certificate Map(將憑證映射到負載均衡器)
gcloud certificate-manager maps create my-cert-map
gcloud certificate-manager maps entries create my-cert-entry \
--map=my-cert-map \
--certificates=my-cert \
--hostname="example.com"
# 在 Target Proxy 使用 Certificate Map
gcloud compute target-https-proxies update my-https-proxy \
--certificate-map=my-cert-map \
--global
Cloud CDN
Cloud CDN 整合在 Global ALB 上,把靜態資源快取到邊緣節點:
快取模式
| 模式 | 說明 | 適合場景 |
|---|---|---|
CACHE_ALL_STATIC | 自動快取 CSS/JS/圖片等靜態類型 | 一般 Web 應用(預設行為) |
USE_ORIGIN_HEADERS | 遵守 origin 的 Cache-Control / Expires Header | 需要精確控制 TTL |
FORCE_CACHE_ALL | 快取所有回應,包含 HTML | ⚠️ 危險,可能快取動態頁面 |
啟用 Cloud CDN
# 在後端服務上啟用 CDN
gcloud compute backend-services update my-backend \
--enable-cdn \
--cache-mode=CACHE_ALL_STATIC \
--default-ttl=3600 \ # 預設快取 1 小時
--max-ttl=86400 \ # 最長快取 24 小時
--global
快取失效(Cache Invalidation)
# 清除特定路徑的快取
gcloud compute url-maps invalidate-cdn-cache my-url-map \
--path="/static/*" \
--global
# 清除全部快取
gcloud compute url-maps invalidate-cdn-cache my-url-map \
--path="/*" \
--global
Cache Tags(2024,精細失效)
# Origin 在 HTTP Response Header 設定 Cache-Tag
# Cache-Tag: product-123,category-electronics
# 按 tag 精確失效(不影響其他快取)
gcloud compute url-maps invalidate-cdn-cache my-url-map \
--tags=product-123 \
--global
⚠️ 注意:Cloud CDN 只支援 Global External ALB(及 classic ALB),不支援 Regional ALB 或 Internal ALB。
Cloud Armor:WAF 與 DDoS 防護
Cloud Armor 掛在 ALB 前面,幫你擋 L3/L4 的 DDoS,也做 L7 的 WAF:
安全政策架構
Internet → Cloud Armor Security Policy → ALB → Backend
├── Rule 1: IP 封鎖
├── Rule 2: 地區限制
├── Rule 3: WAF 規則(XSS、SQLi)
├── Rule 4: Rate Limiting
└── Default Rule: allow/deny
建立安全政策
# 建立安全政策(預設允許所有)
gcloud compute security-policies create my-security-policy \
--description="Production WAF policy"
# 規則 1:封鎖特定 IP
gcloud compute security-policies rules create 1000 \
--security-policy=my-security-policy \
--expression="inIpRange(origin.ip, '192.168.1.0/24')" \
--action=deny-403 \
--description="Block internal subnet"
# 規則 2:地區限制(只允許台灣、日本、美國)
gcloud compute security-policies rules create 2000 \
--security-policy=my-security-policy \
--expression="origin.region_code != 'TW' && origin.region_code != 'JP' && origin.region_code != 'US'" \
--action=deny-403 \
--description="Geo restriction"
# 規則 3:WAF — 防護 XSS
gcloud compute security-policies rules create 3000 \
--security-policy=my-security-policy \
--expression="evaluatePreconfiguredExpr('xss-stable')" \
--action=deny-403 \
--description="XSS protection"
# 規則 4:WAF — 防護 SQL Injection
gcloud compute security-policies rules create 3001 \
--security-policy=my-security-policy \
--expression="evaluatePreconfiguredExpr('sqli-stable')" \
--action=deny-403
# 規則 5:Rate Limiting(每 IP 每分鐘 100 次)
gcloud compute security-policies rules create 4000 \
--security-policy=my-security-policy \
--expression="true" \
--action=rate-based-ban \
--rate-limit-threshold-count=100 \
--rate-limit-threshold-interval-sec=60 \
--ban-duration-sec=600
# 綁定到後端服務
gcloud compute backend-services update my-backend \
--security-policy=my-security-policy \
--global
WAF 預設規則集(Preconfigured Expressions)
| 規則名稱 | 防護類型 |
|---|---|
xss-stable | Cross-Site Scripting |
sqli-stable | SQL Injection |
lfi-stable | Local File Inclusion(2024+) |
rfi-stable | Remote File Inclusion(2024+) |
rce-stable | Remote Code Execution |
scannerdetection-stable | 掃描器偵測 |
健康檢查詳解
健康檢查(Health Check)負責決定哪些後端實例可以收流量:
# HTTP 健康檢查(最常用)
gcloud compute health-checks create http my-hc \
--port=8080 \
--request-path=/health \
--check-interval=10 \ # 每 10 秒檢查一次
--timeout=5 \ # 5 秒超時
--unhealthy-threshold=2 \ # 連續 2 次失敗 → 不健康
--healthy-threshold=1 # 連續 1 次成功 → 健康
# TCP 健康檢查(不支援 HTTP 的服務)
gcloud compute health-checks create tcp my-tcp-hc \
--port=3306 # 例如 MySQL 代理
健康檢查 vs 後端行為:
- 不健康的後端 → ALB 不再分配流量
- MIG 的自動修復(auto-healing)也使用健康檢查,發現不健康 → 自動替換 VM
Passthrough Network Load Balancer
Passthrough NLB 直接把封包轉過去,不做 proxy,所以原始來源 IP 會保留下來:
# 建立 Passthrough NLB 的 Forwarding Rule
gcloud compute forwarding-rules create my-passthrough-nlb \
--region=asia-east1 \
--ip-protocol=TCP \
--ports=80,443 \
--backend-service=my-backend-service \
--load-balancing-scheme=EXTERNAL
Passthrough NLB vs TCP Proxy NLB:
| 特性 | Passthrough NLB | TCP Proxy NLB |
|---|---|---|
| 連線方式 | 直通(Direct Server Return) | Proxy |
| 原始 IP | ✅ 保留 | ❌ 看到 LB IP |
| SSL 終止 | ❌(應用程式處理) | ✅ |
| 全球範圍 | ❌ 區域 | ✅ 全球 |
| 適合 | 需要原始 IP(遊戲、IoT) | 一般 TCP 應用 |
多區域高可用架構設計
┌──────────────────────┐
用戶 ──────────────▶│ Global ALB │
│ (Anycast IP) │
└────────┬─────────────┘
│
┌──────────────┼──────────────┐
▼ ▼ ▼
[asia-east1] [us-central1] [europe-west1]
MIG (2~10) MIG (2~10) MIG (2~10)
│ │ │
Cloud SQL HA Cloud SQL HA Cloud SQL HA
(region replica) (primary) (region replica)
設定多區域後端:
# 加入多個區域的 MIG 作為後端
gcloud compute backend-services add-backend my-backend \
--instance-group=mig-asia \
--instance-group-region=asia-east1 \
--balancing-mode=UTILIZATION \
--max-utilization=0.8 \
--global
gcloud compute backend-services add-backend my-backend \
--instance-group=mig-us \
--instance-group-region=us-central1 \
--balancing-mode=UTILIZATION \
--max-utilization=0.8 \
--global
Global ALB 會優先把流量導到離用戶最近、而且健康的後端;萬一近端掛了,就自動 failover 到其他區域。
ACE 考試重點整理
選型決策矩陣
| 需求 | 選擇 |
|---|---|
| 全球用戶,L7 HTTP/HTTPS | Global Application LB |
| 區域內用戶,資料合規 | Regional Application LB |
| TCP/UDP,需保留原始 IP | Passthrough Network LB |
| 微服務內部 HTTP 路由 | Internal Application LB |
| 微服務內部 TCP 路由 | Internal Network LB |
| Cloud Run + 自訂域名 + CDN | Global ALB + Serverless NEG |
| 需要 WAF/DDoS 防護 | Cloud Armor(掛在 ALB 上) |
| 靜態資源快取 | Cloud CDN(只支援外部 ALB) |
必背知識點
- 2024 命名變更:HTTP(S) LB → ALB,TCP/UDP LB → NLB
- Global ALB 使用 Anycast IP,Regional ALB 使用區域 IP
- Internal ALB 不支援 Cloud CDN
- MIG 才有 Autoscaling 和 Auto-healing,Unmanaged IG 沒有
- Serverless NEG 是 Cloud Run 整合 ALB 的方式
- Cloud Armor 規則順序:數字越小優先級越高
- FORCE_CACHE_ALL 有風險,會快取動態頁面
常見陷阱題
Q:要對全球用戶提供低延遲服務,需要什麼架構? A:Global ALB + 多區域 MIG。Global ALB 的 Anycast 會將用戶路由到最近的區域。
Q:Cloud CDN 可以用在 Internal ALB 嗎? A:不行。Cloud CDN 只能用在外部(External)ALB。
Q:如何確保後端 VM 被替換時服務不中斷? A:使用 MIG 的 Auto-healing + Health Check,不健康的 VM 自動替換,ALB 在替換期間不發送流量給不健康實例。
Q:如何只允許特定國家的流量?
A:使用 Cloud Armor 建立地區限制規則(origin.region_code)。
Q:ALB 元件建立順序為何? A:Health Check → Backend Service → URL Map → Target Proxy → Forwarding Rule(由內而外)
總結
GCP 負載均衡是 ACE 考試的高頻核心考點,幾個關鍵記起來:
- 命名:2024 年 ALB 取代 HTTP(S) LB,NLB 取代 TCP/UDP LB
- 架構:Forwarding Rule → Target Proxy → URL Map → Backend Service
- 後端:MIG(有 Autoscaling)或 NEG(Serverless NEG 用於 Cloud Run)
- CDN:只支援外部 ALB,三種快取模式
- Cloud Armor:規則優先順序(數字小 = 高優先),WAF 預設規則集
- 多區域 HA:Global ALB + 多區域 MIG 是標準高可用架構
下一課 GCP-110:VPC 進階網路設計,深入探討 Shared VPC、VPC Peering、Cloud NAT 與 Private Google Access。