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

如何让GCP中K8s自动创建的网络端点组自动删除?

如何自动删除GKE Service注解创建的网络端点组(NEG)

方法1:修改Service注解启用NEG自动删除

你当前的注解仅指定了NEG名称,未开启自动清理规则。只需在注解中为目标端口添加"auto_delete": true参数,当关联的Kubernetes Service被删除时,GCP会自动清理对应的NEG(前提是该NEG未被其他GCP资源绑定)。

修改后的注解代码:

cloud.google.com/neg: '{"exposed_ports": {"80":{"name": "app2-service-80-neg", "auto_delete": true}}}'

方法2:通过Terraform管控NEG生命周期

如果使用Terraform部署Kubernetes Service和关联的GCP负载均衡,需确保资源销毁顺序正确:

  • 在定义kubernetes_service资源时,包含上述带auto_delete的注解;
  • 为GCP负载均衡后端服务(google_compute_backend_service)添加依赖,使其依赖于Kubernetes Service;
  • 配置Terraform的lifecycle规则,确保后端服务先于NEG被销毁,避免NEG因被绑定而无法自动删除。

示例Terraform核心片段:

resource "kubernetes_service" "app_service" {
  metadata {
    name = "app2-service"
    annotations = {
      "cloud.google.com/neg" = jsonencode({
        exposed_ports = {
          "80" = {
            name        = "app2-service-80-neg"
            auto_delete = true
          }
        }
      })
    }
  }

  # ... 其他Service配置 ...
}

resource "google_compute_backend_service" "app_backend" {
  name        = "app-backend-service"
  # ... 其他后端服务配置 ...

  backend {
    group = kubernetes_service.app_service.metadata.0.annotations["cloud.google.com/neg"]
  }

  lifecycle {
    create_before_destroy = true
  }
}

方法3:临时清理遗留NEG(应急场景)

如果已经有未被清理的NEG,可以用gcloud命令手动删除:

  • 删除单个NEG:
gcloud compute network-endpoint-groups delete app2-service-80-neg --region=<你的集群所在区域> --quiet
  • 批量删除无关联的NEG(过滤出未绑定任何后端服务的NEG):
REGION="你的集群区域"
gcloud compute network-endpoint-groups list --region=$REGION --format="value(name)" | while read NEG_NAME; do
  BACKENDS=$(gcloud compute network-endpoint-groups describe $NEG_NAME --region=$REGION --format="value(backends)")
  if [ -z "$BACKENDS" ]; then
    gcloud compute network-endpoint-groups delete $NEG_NAME --region=$REGION --quiet
  fi
done

关键注意事项

  • 启用auto_delete后,只有当NEG未被任何GCP资源(如后端服务、负载均衡器)关联时,才会被自动删除。因此需确保销毁顺序为:负载均衡器 → 后端服务 → Kubernetes Service。
  • 如果Terraform销毁时提示VPC无法删除,需检查VPC内是否还有残留的NEG或其他关联资源,可通过gcloud compute network-endpoint-groups list --filter="network:你的VPC名称"排查。

内容的提问来源于stack exchange,提问作者Gary Turner

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 22:20:40