You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Terraform为GKE Autopilot集群部署网络直通负载均衡器

解决方案:用Terraform基于GKE节点池创建区域NEG实现网络直通负载均衡器

核心思路是利用GKE Autopilot节点池的关联属性,创建GCE_VM_IP类型(或GCE_VM_IP_PORT类型)的区域NEG(Network Endpoint Group),该NEG会自动同步Autopilot工作节点的增减,无需手动添加实例,再将其绑定到网络负载均衡器的后端服务即可。

步骤1:定义GKE Autopilot集群(若未创建)

先通过Terraform声明Autopilot集群资源:

resource "google_container_cluster" "autopilot" {
  name     = "autopilot-cluster"
  location = "us-central1"

  enable_autopilot = true

  master_auth {
    username = ""
    password = ""

    client_certificate_config {
      issue_client_certificate = false
    }
  }
}

步骤2:创建关联Autopilot节点池的区域NEG

使用google_compute_region_network_endpoint_group资源,通过集群ID和默认节点池名称自动关联Autopilot节点,生成包含所有工作节点的NEG:

resource "google_compute_region_network_endpoint_group" "gke_nodes_neg" {
  name                  = "gke-autopilot-nodes-neg"
  region                = "us-central1"
  network_endpoint_type = "GCE_VM_IP" # 若需指定端口可改用GCE_VM_IP_PORT

  gke_cluster {
    cluster = google_container_cluster.autopilot.id
  }

  gke_node_pool {
    node_pool = google_container_cluster.autopilot.default_node_pool.name
  }
}

步骤3:创建负载均衡器后端服务

将上述NEG绑定到后端服务,配置健康检查和负载均衡策略:

resource "google_compute_region_backend_service" "lb_backend" {
  name                  = "gke-autopilot-lb-backend"
  region                = "us-central1"
  protocol              = "TCP" # 根据服务协议调整为UDP等
  load_balancing_scheme = "EXTERNAL" # 内部LB可改用INTERNAL

  backend {
    group = google_compute_region_network_endpoint_group.gke_nodes_neg.id
  }

  health_checks = [google_compute_health_check.tcp_health_check.id]
}

# 配套健康检查配置
resource "google_compute_health_check" "tcp_health_check" {
  name               = "tcp-health-check"
  check_interval_sec = 5
  timeout_sec        = 5

  tcp_health_check {
    port = 80 # 对应服务监听端口
  }
}

步骤4:创建转发规则与代理(完成LB部署)

以外部TCP负载均衡器为例,创建目标代理和转发规则:

# 目标TCP代理
resource "google_compute_target_tcp_proxy" "lb_proxy" {
  name            = "gke-autopilot-tcp-proxy"
  backend_service = google_compute_region_backend_service.lb_backend.id
}

# 转发规则(绑定公网IP)
resource "google_compute_forwarding_rule" "lb_forwarding_rule" {
  name       = "gke-autopilot-forwarding-rule"
  region     = "us-central1"
  ip_address = google_compute_global_address.lb_ip.address
  ip_protocol = "TCP"
  port_range  = "80"
  target      = google_compute_target_tcp_proxy.lb_proxy.id
}

# 可选:静态公网IP
resource "google_compute_global_address" "lb_ip" {
  name = "gke-autopilot-lb-ip"
}

关键说明

  • 该方案通过GKE节点池直接关联NEG,Autopilot节点的增减会自动同步到NEG中,无需手动维护实例列表,和你之前用YAML部署时GCP自动创建非托管实例组的逻辑等效。
  • 确保所有资源的区域与集群区域一致,避免跨区域兼容性问题。

内容的提问来源于stack exchange,提问作者Jacopo Terrinoni

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 02:35:01