PHP Warning: Invalid argument supplied for foreach() in /usr/share/nginx/html/wp-content/themes/dux/widgets/widget-index.php on line 28
Warning: Invalid argument supplied for foreach() in /usr/share/nginx/html/wp-content/themes/dux/widgets/widget-index.php on line 28
引言:为什么Google Cloud网络架构是云上应用的基石
在Google Cloud Platform(GCP)的众多服务中,网络架构往往是被低估却又至关重要的基础层。无论你运行的是Cloud Run微服务、GKE集群、还是Compute Engine虚拟机,底层的VPC网络设计直接决定了应用的可扩展性、安全性和性能表现。一个糟糕的网络架构可能导致跨区域延迟飙升、安全暴露面过大、甚至流量成本失控。
本文将从生产级视角出发,系统讲解Google Cloud网络的核心组件:VPC网络设计模式、共享VPC架构、Cloud Load Balancing四大类型的选择策略、Cloud CDN加速与缓存优化、以及Cloud Armor WAF防护规则编写。每个部分都附带Terraform代码示例,确保你可以直接将这些模式应用到自己的基础设施中。

VPC网络架构:从单项目到共享VPC的演进
VPC核心概念与设计原则
Google Cloud的VPC(Virtual Private Cloud)与传统云厂商的VPC有一个本质区别:GCP的VPC是全球性的资源,而非区域性的。这意味着一个VPC可以跨越多个Region,子网(Subnet)才是区域级别的资源。这一设计带来了几个关键优势:
- 同一VPC内跨Region通信无需VPN或对等连接,延迟更低
- 子网可以按Region独立规划CIDR,避免IP冲突
- 全局防火墙规则对整个VPC生效,简化安全策略管理
在设计VPC时,需要遵循以下原则:
| 原则 | 说明 | 推荐值 |
|---|---|---|
| CIDR预留空间 | 主CIDR块至少预留/16,为未来扩展留足空间 | 10.0.0.0/16(65536个IP) |
| 子网CIDR粒度 | 每个子网根据实际负载规划,避免浪费 | /24(256个IP)起步 |
| 环境隔离 | 生产/预发/开发使用独立子网 | 不同CIDR段隔离 |
| 区域分布 | 每个部署Region至少一个子网 | 按Region分配连续CIDR |
生产级VPC Terraform配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49 # vpc-main.tf
resource "google_compute_network" "main" {
name = "vpc-production"
auto_create_subnetworks = false # 必须关闭自动创建子网
routing_mode = "GLOBAL" # 全局路由,跨Region通信最优
description = "Production VPC with multi-region subnets"
}
# 生产环境子网 - us-central1
resource "google_compute_subnetwork" "prod_us_central" {
name = "subnet-prod-us-central1"
ip_cidr_range = "10.0.1.0/24"
region = "us-central1"
network = google_compute_network.main.id
# 启用Private Google Access,无需NAT即可访问GCP API
private_ip_google_access = true
# 启用VPC Flow Logs用于网络审计
log_config {
aggregation_interval = "INTERVAL_5_SEC"
flow_sampling = 0.5
metadata = "INCLUDE_ALL_METADATA"
}
}
# 生产环境子网 - asia-east1
resource "google_compute_subnetwork" "prod_asia_east" {
name = "subnet-prod-asia-east1"
ip_cidr_range = "10.0.2.0/24"
region = "asia-east1"
network = google_compute_network.main.id
private_ip_google_access = true
log_config {
aggregation_interval = "INTERVAL_5_SEC"
flow_sampling = 0.5
metadata = "INCLUDE_ALL_METADATA"
}
}
# 开发环境子网(隔离)
resource "google_compute_subnetwork" "dev_us_central" {
name = "subnet-dev-us-central1"
ip_cidr_range = "10.1.1.0/24"
region = "us-central1"
network = google_compute_network.main.id
private_ip_google_access = true
}
共享VPC:多项目架构的最佳实践
当组织规模扩大后,多个GCP项目需要共享同一个VPC网络。共享VPC(Shared VPC)允许一个宿主项目(Host Project)拥有VPC,而多个服务项目(Service Projects)可以使用其中的子网。这种模式的核心价值在于:
- 网络集中管理:网络团队在宿主项目统一管理防火墙规则、路由和子网
- 项目隔离:服务项目只能使用被授权的子网,无法越权访问其他子网
- 成本归属清晰:每个服务项目的资源使用可以独立计费
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 # shared-vpc.tf
# 宿主项目中启用共享VPC
resource "google_compute_shared_vpc" "main" {
host_project = var.host_project_id
# 关联服务项目
service_projects = [
var.service_project_a_id,
var.service_project_b_id,
]
}
# 为服务项目授权特定子网
resource "google_compute_subnetwork_iam_binding" "service_a_subnet" {
project = var.host_project_id
subnetwork = google_compute_subnetwork.prod_us_central.name
region = google_compute_subnetwork.prod_us_central.region
role = "roles/compute.networkUser"
members = [
"serviceAccount:${var.service_project_a_id}@appspot.gserviceaccount.com",
]
}
Cloud Load Balancing:四大类型的选择与配置

负载均衡选型决策矩阵
Google Cloud提供四种主要的负载均衡器,选择正确的类型是架构设计的第一步:
| 类型 | 流量类型 | 跨Region | 典型场景 | 后端支持 |
|---|---|---|---|---|
| Global External HTTP(S) | L7 HTTP/HTTPS | 是 | Web应用、API网关、CDN回源 | GCE、GKE、Cloud Run、Cloud Storage |
| Regional External TCP/SSL | L4 TCP/TLS | 否 | 数据库代理、非HTTP协议 | GCE、GKE、NEG |
| Regional Internal TCP/UDP | L4 内部TCP/UDP | 否 | 内部微服务通信、数据库负载均衡 | GCE、GKE |
| Internal HTTP(S) | L7 内部HTTP | 否 | 服务网格内部流量、Envoy代理 | GCE、GKE、NEG |
选择的核心逻辑:
- 面向公网的Web应用 → Global External HTTP(S) LB,利用全球Anycast IP实现就近接入
- 需要内部服务发现和流量管理 → Internal HTTP(S) LB,配合Traffic Director实现服务网格
- 非HTTP协议或数据库 → Regional Internal TCP/UDP LB
Global External HTTP(S) Load Balancer生产配置
这是最常用的负载均衡器,也是Cloud CDN和Cloud Armor的前置依赖。下面是完整的Terraform配置:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113 # global-lb.tf
# 静态外部IP
resource "google_compute_global_address" "lb_ip" {
name = "global-lb-ip"
}
# 托管SSL证书(推荐生产环境使用)
resource "google_compute_managed_ssl_certificate" "main" {
name = "ssl-cert-example-com"
managed {
domains = ["api.example.com"]
}
lifecycle {
create_before_destroy = true
}
}
# 后端服务 - Cloud Run
resource "google_compute_backend_service" "cloud_run_backend" {
name = "backend-cloud-run"
load_balancing_scheme = "EXTERNAL_MANAGED"
protocol = "HTTPS"
backend {
group = google_compute_region_network_endpoint_group.cloud_run_neg.id
}
# 健康检查配置
health_checks = [google_compute_health_check.http_hc.id]
# 超时与重试
timeout_sec = 30
# 启用Cloud CDN(后面详细讲)
enable_cdn = true
# 连接排空(维护期间优雅停机)
connection_draining_timeout_sec = 300
# 安全策略(Cloud Armor,后面详细讲)
security_policy = google_compute_security_policy.armor_policy.id
}
# Cloud Run NEG
resource "google_compute_region_network_endpoint_group" "cloud_run_neg" {
name = "neg-cloud-run-api"
region = "us-central1"
network_endpoint_type = "SERVERLESS"
cloud_run {
service = var.cloud_run_service_name
}
}
# 健康检查
resource "google_compute_health_check" "http_hc" {
name = "hc-http-api"
check_interval_sec = 10
timeout_sec = 5
healthy_threshold = 2
unhealthy_threshold = 3
http_health_check {
port = 443
request_path = "/healthz"
}
}
# URL Map - 路由规则
resource "google_compute_url_map" "main" {
name = "url-map-main"
default_service = google_compute_backend_service.cloud_run_backend.id
# 路径路由规则
path_matcher {
name = "api-routes"
default_service = google_compute_backend_service.cloud_run_backend.id
path_rule {
paths = ["/api/v2/*"]
service = google_compute_backend_service.api_v2_backend.id
}
path_rule {
paths = ["/static/*"]
service = google_compute_backend_bucket.static_bucket.id
}
}
host_rule {
hosts = ["api.example.com"]
path_matcher = "api-routes"
}
}
# HTTPS代理
resource "google_compute_target_https_proxy" "main" {
name = "https-proxy-main"
url_map = google_compute_url_map.main.id
ssl_certificates = [google_compute_managed_ssl_certificate.main.id]
quic_override = "ENABLE" # 启用QUIC协议,降低连接延迟
}
# 全局转发规则
resource "google_compute_global_forwarding_rule" "https" {
name = "fr-https-main"
load_balancing_scheme = "EXTERNAL_MANAGED"
ip_address = google_compute_global_address.lb_ip.id
port_range = "443"
target = google_compute_target_https_proxy.main.id
}
负载均衡性能调优关键参数
在生产环境中,以下几个参数直接影响用户体验和成本:
- 连接排空超时(connection_draining_timeout_sec):设置为300秒,确保部署期间进行中的请求不会中断
- QUIC协议(quic_override: ENABLE):启用QUIC可将握手延迟从3个RTT降低到0-1个RTT,对移动端用户尤其有效
- 会话亲和性(sessionAffinity):对于有状态服务(如WebSocket),设置为CLIENT_IP,避免长连接中断
- 最大RPS速率限制(maxRatePerEndpoint):防止单个后端过载,Cloud Run建议设为容器concurrency的80%
Cloud CDN:缓存策略深度优化

Cloud CDN工作原理与缓存层级
Cloud CDN利用Google全球边缘网络(100+个PoP节点),将内容缓存到离用户最近的位置。理解其缓存层级对于正确配置缓存策略至关重要:
- 边缘缓存:分布在全球各PoP节点,缓存命中时延迟最低(通常<10ms)
- 中间缓存:区域级缓存层,降低回源频率
- 源站:后端服务,最慢但数据最新
缓存决策流程:请求到达边缘节点 → 检查边缘缓存 → 未命中则查中间缓存 → 未命中则回源获取内容 → 沿途缓存响应。
缓存策略配置实战
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51 # cloud-cdn.tf
# 在Backend Service上启用CDN
resource "google_compute_backend_service" "cdn_backend" {
name = "backend-with-cdn"
enable_cdn = true
cdn_policy {
# 缓存模式:CACHE_ALL_STATIC 自动缓存静态资源
# FORCE_CACHE_ALL 强制缓存所有响应(谨慎使用)
# USE_ORIGIN_HEADERS 尊重源站Cache-Control头
cache_mode = "CACHE_ALL_STATIC"
# 客户端最大缓存时间
client_ttl = 3600 # 1小时
# CDN边缘节点最大缓存时间
default_ttl = 86400 # 24小时
# 负缓存时间(对错误响应也缓存,防止源站被击穿)
negative_caching = true
negative_caching_policy {
code = 404
ttl = 60 # 404缓存60秒
}
negative_caching_policy {
code = 500
ttl = 10 # 500缓存10秒,快速重试
}
# 当源站未提供Cache-Control时的默认行为
serve_while_stale = 86400 # 过期后仍提供旧内容最多24小时
# 浏览器端TTL(覆盖源站的s-maxage)
max_ttl = 604800 # 7天
# 对带查询参数的请求也缓存
cache_key_policy {
include_query_string = true
query_string_blacklist = ["utm_source", "utm_medium", "utm_campaign"]
include_http_headers = ["Authorization"]
include_named_cookies = ["session_id"]
}
}
backend {
group = google_compute_region_network_endpoint_group.cloud_run_neg.id
}
load_balancing_scheme = "EXTERNAL_MANAGED"
protocol = "HTTPS"
}
缓存失效与版本化策略
缓存最大的挑战不是启用,而是失效。以下是三种常用的缓存失效策略:
策略一:内容哈希版本化——在URL中嵌入内容哈希,如
1 | /static/app.a1b2c3.js |
。每次部署时哈希变化,URL自然不同,旧缓存自动失效。这是最推荐的方式,因为:
- 无需主动失效操作
- 新旧版本可共存,无中间状态
- CDN节点无需额外请求
策略二:Cache-Control精细化控制——在源站响应中设置精细的Cache-Control头:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 # Python Flask示例
@app.route('/api/data')
def get_data():
response = jsonify(data)
# API响应:短缓存,stale-while-revalidate允许过期后异步刷新
response.headers['Cache-Control'] = \
'public, max-age=60, s-maxage=300, stale-while-revalidate=600'
return response
@app.route('/static/manifest.json')
def manifest():
response = jsonify(manifest_data)
# 短缓存+立即失效:每次都重新验证
response.headers['Cache-Control'] = \
'public, max-age=0, s-maxage=0, must-revalidate'
# ETag支持条件请求
response.headers['ETag'] = f'"{hashlib.md5(content).hexdigest()}"'
return response
策略三:主动失效API——当业务要求缓存立即清除时,使用Cloud CDN的Invalidation API:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 # 缓存失效脚本
import google.auth
from google.cloud import compute_v1
def invalidate_cdn_cache(project_id, url_map_name, path):
"""主动失效CDN缓存"""
client = compute_v1.UrlMapsClient()
request = compute_v1.InvalidateCacheUrlMapRequest()
request.path = path # 如 "/api/data/*" 或 "/static/*"
operation = client.invalidate(
project=project_id,
url_map=url_map_name,
cache_invalidation_rule_resource=request,
)
# 等待操作完成
result = operation.result()
print(f"Invalidation completed: {path}")
return result
# 失效指定路径
invalidate_cdn_cache("my-project", "url-map-main", "/api/v2/*")
CDN性能监控与成本优化
CDN效果的核心指标是缓存命中率(Cache Hit Ratio)。目标是将命中率提升到90%以上。监控方法:
1
2
3
4
5
6
7
8
9
10
11 # 使用gcloud监控CDN指标
gcloud monitoring metrics list \
--filter="metric.type:cdn"
# 核心监控指标
# - loadbalancing.googleapis.com/https/request_count
# 按response_code_class分组,2xx/3xx(缓存命中)/4xx/5xx
# - loadbalancing.googleapis.com/https/total_latencies
# 缓存命中 vs 回源的延迟对比
# - loadbalancing.googleapis.com/https/backend_request_count
# 回源请求数(越低越好)
成本优化要点:
- 静态资源启用压缩(Gzip/Brotli),CDN自动对text/、application/json等MIME类型压缩,带宽成本降低40-60%
- 图片使用WebP/AVIF格式,配合质量参数控制体积
- 合理设置
1s-maxage
,让CDN缓存更久,
1max-age可设短一些确保用户端刷新
Cloud Armor:WAF防护与DDoS缓解
Cloud Armor防护能力概览
Cloud Armor是GCP的Web应用防火墙(WAF)和DDoS防护服务,直接与Global External HTTP(S) Load Balancer集成。其核心能力包括:
- L3/L4 DDoS防护:自动缓解网络层和传输层的DDoS攻击,无需配置
- L7 WAF规则:基于预定义规则和自定义规则过滤恶意请求
- 自适应保护(Adaptive Protection):利用ML模型自动检测异常流量并生成建议规则
- 地理封禁:按国家/地区过滤流量
- 速率限制:按客户端IP或HTTP属性限制请求速率
安全策略配置实战
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117 # cloud-armor.tf
resource "google_compute_security_policy" "armor_policy" {
name = "security-policy-production"
description = "Production WAF policy with adaptive protection"
# 启用自适应保护(ML异常检测)
adaptive_protection_config {
layer_7_ddos_defense_config {
enable = true
rule_visibility = "STANDARD" # 日志中可见异常检测信息
}
}
# 规则1:封禁高风险地区(按业务需求调整)
rule {
action = "deny(403)"
priority = 1000
match {
versioned_expr = "SRC_IPS_V1"
config {
src_ip_ranges = [
# 封禁已知恶意IP段(示例)
"203.0.113.0/24",
"198.51.100.0/24",
]
}
}
description = "Block known malicious IP ranges"
}
# 规则2:SQL注入防护
rule {
action = "deny(403)"
priority = 2000
match {
expr {
expression = "evaluatePreconfiguredExpr('sqli-v33-stable')"
}
}
description = "Block SQL injection attempts"
}
# 规则3:XSS防护
rule {
action = "deny(403)"
priority = 3000
match {
expr {
expression = "evaluatePreconfiguredExpr('xss-v33-stable')"
}
}
description = "Block XSS attempts"
}
# 规则4:速率限制(单IP每分钟最多600请求)
rule {
action = "rate_based_ban" # 超过阈值后封禁
priority = 4000
rate_limit_options {
rate_limit_threshold {
count = 600
interval_sec = 60
}
ban_duration_sec = 600 # 封禁10分钟
enforce_on_key = "IP" # 按IP限速
# 超限后的动作
ban_action {
deny_status_code = 429
}
}
match {
versioned_expr = "SRC_IPS_V1"
config {
src_ip_ranges = ["*"]
}
}
description = "Rate limit: 600 req/min per IP"
}
# 规则5:地理限制(仅允许特定国家)
rule {
action = "allow"
priority = 5000
match {
expr {
expression = "origin.region_code == 'CN' || origin.region_code == 'US' || origin.region_code == 'JP'"
}
}
description = "Allow traffic from CN, US, JP only"
}
# 规则6:阻止 bots(检测常见爬虫User-Agent)
rule {
action = "deny(403)"
priority = 6000
match {
expr {
expression = "has(request.headers['user-agent']) && request.headers['user-agent'].contains('python-requests')"
}
}
description = "Block automated scraping bots"
}
# 默认规则:拒绝所有未匹配的流量
rule {
action = "deny(403)"
priority = 2147483647 # 最低优先级
match {
versioned_expr = "SRC_IPS_V1"
config {
src_ip_ranges = ["*"]
}
}
description = "Default deny-all rule"
}
}
Cloud Armor高级自定义规则
当预定义规则无法满足需求时,可以使用CEL(Common Expression Language)编写自定义规则。以下是几个实用的自定义规则示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 # 自定义规则:阻止无Referer的POST请求(防CSRF)
expression = """
request.method == 'POST' &&
!has(request.headers['referer'])
"""
# 自定义规则:限制API路径的请求体大小(防大文件上传攻击)
expression = """
request.path.startsWith('/api/upload') &&
int(request.headers['content-length']) > 10485760
"""
# 自定义规则:检测路径遍历攻击
expression = """
request.path.contains('../') ||
request.path.contains('..\\') ||
request.path.contains('%2e%2e')
"""
# 自定义规则:限制特定路径的速率(API接口保护)
expression = """
request.path.matches('/api/v[0-9]+/auth/.*')
"""
# 配合 rate_limit_options 实现API接口级别的速率限制
# threshold: count=20, interval_sec=60, enforce_on_key=IP
Cloud Armor日志分析与告警
Cloud Armor的日志是安全运营的核心数据来源。通过将日志导出到BigQuery,可以实现深度分析:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42 # 日志导出到BigQuery
resource "google_logging_project_sink" "armor_logs" {
name = "armor-logs-sink"
destination = "bigquery.googleapis.com/projects/${var.project_id}/datasets/armor_logs"
filter = "resource.type="http_load_balancer" AND jsonPayload.enforcedSecurityPolicy.outcome="DENY""
unique_writer_identity = true
}
# BigQuery分析查询示例
# 查看被拦截的Top IP
"""
SELECT
jsonPayload.enforcedSecurityPolicy.clientIp AS client_ip,
COUNT(*) AS blocked_count,
ARRAY_AGG(DISTINCT jsonPayload.enforcedSecurityPolicy.name) AS triggered_rules
FROM `project.armor_logs.requests_*`
WHERE _TABLE_SUFFIX >= FORMAT_DATE('%Y%m%d', DATE_SUB(CURRENT_DATE(), INTERVAL 7 DAY))
GROUP BY client_ip
ORDER BY blocked_count DESC
LIMIT 20
"""
# Cloud Monitoring告警策略
resource "google_monitoring_alert_policy" "armor_alert" {
display_name = "High Block Rate Alert"
conditions {
condition_threshold {
filter = "resource.type="http_load_balancer""
duration = "300s"
comparison = "COMPARISON_GT"
threshold_value = 1000 # 5分钟内超过1000个被拦截请求
aggregations {
alignment_period = "300s"
per_series_aligner = "ALIGN_RATE"
}
}
}
notification_channels = [google_monitoring_notification_channel.email.id]
}
VPC防火墙规则与安全纵深防御
VPC防火墙规则最佳实践
VPC防火墙规则工作在实例级别(不是子网级别),是最基础的网络隔离手段。生产环境建议遵循最小权限原则:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55 # firewall-rules.tf
# 拒绝所有入站(默认行为,但显式声明更安全)
resource "google_compute_firewall" "deny_all_ingress" {
name = "deny-all-ingress"
network = google_compute_network.main.id
direction = "INGRESS"
action = "DENY"
priority = 65534
ranges = ["0.0.0.0/0"]
# 仅对特定服务账号生效
target_service_accounts = [var.service_account_email]
}
# 仅允许Load Balancer健康检查IP段
resource "google_compute_firewall" "allow_lb_healthcheck" {
name = "allow-lb-healthcheck"
network = google_compute_network.main.id
direction = "INGRESS"
action = "ALLOW"
priority = 1000
# GCP Load Balancer健康检查源IP段
ranges = [
"35.191.0.0/16", # 全球HTTP(S) LB健康检查
"130.211.0.0/22", # 全球HTTP(S) LB健康检查(旧段)
]
allow {
protocol = "tcp"
ports = ["80", "443"]
}
target_service_accounts = [var.service_account_email]
}
# 仅允许内部子网间通信
resource "google_compute_firewall" "allow_internal" {
name = "allow-internal-traffic"
network = google_compute_network.main.id
direction = "INGRESS"
action = "ALLOW"
priority = 1000
ranges = ["10.0.0.0/16"] # VPC CIDR
allow {
protocol = "tcp"
}
allow {
protocol = "udp"
}
allow {
protocol = "icmp"
}
}
NAT网关与Private GKE集群
生产环境中,实例不应拥有外部IP。Cloud NAT让没有外部IP的资源可以安全地访问互联网(出站方向),同时阻止所有入站连接:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 # cloud-nat.tf
resource "google_compute_router" "nat_router" {
name = "nat-router"
region = "us-central1"
network = google_compute_network.main.id
}
resource "google_compute_router_nat" "main" {
name = "nat-gateway"
router = google_compute_router.nat_router.name
region = "us-central1"
# 为每个VM自动分配NAT IP
nat_ip_allocate_option = "AUTO_ONLY"
# 所有子网(含二级IP范围)都走NAT
source_subnetwork_ip_ranges_to_nat = "ALL_SUBNETWORKS_ALL_IP_RANGES"
# 启用端点独立映射(同VM同IP同端口映射到同一NAT端口,
# 避免外部服务误判为端口扫描)
endpoint_types = ["ENDPOINT_TYPE_VM"]
# 日志
log_config {
enable = true
filter = "ERRORS_ONLY" # 仅记录NAT失败,节省成本
}
}
完整架构:多组件协作的端到端流程
将以上组件组合起来,一个生产级Google Cloud网络架构的端到端请求流程如下:
- 用户请求到达Google边缘PoP节点,Global HTTP(S) LB的Anycast IP接收请求
- Cloud Armor在LB层面检查WAF规则,恶意流量被拒绝(403/429)
- Cloud CDN检查边缘缓存,命中则直接返回(延迟<10ms)
- 缓存未命中时,请求转发到后端服务(Cloud Run/GKE/GCE)
- VPC防火墙规则在实例层面二次过滤,仅允许LB健康检查IP段
- 后端响应沿路径缓存,CDN根据Cache-Control决定缓存时间
- 出站请求(如API调用外部服务)通过Cloud NAT访问互联网,无需外部IP
这种架构实现了纵深防御:Cloud Armor在边缘过滤已知攻击 → CDN缓存减轻后端负载 → LB分发流量确保高可用 → VPC防火墙在实例层面二次过滤 → Cloud NAT确保出站安全。每一层都是独立的防护层,即使某一层被突破,其他层仍然提供保护。
成本控制与监控策略
Google Cloud网络服务的计费模式需要注意,以下是最容易超支的项目:
| 服务 | 计费方式 | 优化策略 |
|---|---|---|
| Cloud CDN | 缓存命中免费;回源按流量计费 | 提高缓存命中率>90%,减少回源 |
| Cloud NAT | 按GB出站流量+每小时网关费用 | 仅对需要外网的子网启用;使用private.googleapis.com |
| Global LB | 按转发规则数+流量GB计费 | 多服务共用一个LB(URL Map路由),避免多LB |
| Cloud Armor | 按策略数+规则数+请求量计费 | 合并规则,减少策略数量;adaptive protection仅对关键服务启用 |
| VPC Flow Logs | 按日志量计费(可非常贵) | 调低采样率(flow_sampling=0.1),仅对关键子网启用 |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47 # 监控Dashboard - Terraform配置
resource "google_monitoring_dashboard" "networking" {
dashboard_json = jsonencode({
displayName = "GCP Networking Overview"
mosaicLayout = {
tiles = [
{
width = 6
height = 4
widget = {
title = "CDN Cache Hit Ratio"
xyChart = {
dataSets = [{
timeSeriesQuery = {
timeSeriesFilter = {
filter = "metric.type="loadbalancing.googleapis.com/https/request_count""
aggregation = {
alignmentPeriod = "300s"
perSeriesAligner = "ALIGN_RATE"
groupByFields = ["response_code_class"]
}
}
}
}]
}
}
},
{
width = 6
height = 4
widget = {
title = "Cloud Armor Blocked Requests"
xyChart = {
dataSets = [{
timeSeriesQuery = {
timeSeriesFilter = {
filter = "metric.type="loadbalancing.googleapis.com/https/request_count" resource.type="http_load_balancer""
}
}
}]
}
}
}
]
}
})
}
总结与最佳实践清单
本文深入讲解了Google Cloud网络架构的核心组件。在结束之前,将关键最佳实践整理为清单:
- ✅ VPC设计时关闭auto_create_subnetworks,手动规划子网CIDR
- ✅ 使用共享VPC管理多项目网络,服务项目仅获得授权子网的访问权
- ✅ 面向公网的Web应用选择Global External HTTP(S) LB,启用QUIC协议
- ✅ Cloud CDN使用CACHE_ALL_STATIC模式,配合内容哈希版本化实现无失效缓存
- ✅ Cloud Armor至少配置sqli/xss预定义规则+速率限制+自适应保护
- ✅ VPC防火墙规则遵循最小权限原则,仅开放LB健康检查IP段
- ✅ 无外部IP的实例使用Cloud NAT出站,禁止分配公网IP
- ✅ 启用VPC Flow Logs但降低采样率,避免日志成本失控
- ✅ 所有网络组件统一用Terraform管理,禁止手动控制台操作
- ✅ 监控CDN缓存命中率、LB延迟、Armor拦截量三大核心指标
Google Cloud的网络服务设计理念是安全默认+分层防护。通过VPC隔离、LB流量分发、CDN缓存加速、Armor WAF防护、NAT出站控制的组合,可以在保证性能的同时将攻击面降到最低。记住:网络安全不是单一产品的事,而是架构整体的事。
汤不热吧