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

Terraform部署GCP Compute Engine无互联网访问问题求助

GCP Compute Engine实例无法访问互联网的问题修复

问题背景

通过Terraform部署了两台带静态内网IP的GCP Compute Engine实例,实例间通信正常,但无法访问互联网(可解析域名,但ping不通外部地址)。

遗漏的关键配置及修复方案

1. 未配置Cloud NAT实现公网访问

实例仅配置内部静态IP,无外部IP,无法直接访问公网。需通过Cloud NAT完成地址转换,让无外部IP的实例访问互联网:

添加以下Terraform资源:

# 创建Cloud Router
resource "google_compute_router" "nat_router" {
  name    = "nat-router"
  region  = "us-west1"
  network = google_compute_network.default.id
}

# 配置Cloud NAT规则
resource "google_compute_router_nat" "nat_config" {
  name                               = "nat-config"
  router                             = google_compute_router.nat_router.name
  region                             = "us-west1"
  nat_ip_allocate_option             = "AUTO_ONLY"
  source_subnetwork_ip_ranges_to_nat = "ALL_SUBNETWORKS_ALL_IP_RANGES"
}

2. 缺少出向ICMP防火墙规则

现有allow-icmp规则仅针对入向流量(允许外部ping实例),但实例ping外部需要放行出向ICMP流量:

添加出向ICMP防火墙规则:

resource "google_compute_firewall" "egress_icmp" {
  name = "allow-egress-icmp"
  allow {
    protocol = "icmp"
  }
  direction          = "EGRESS"
  network            = google_compute_network.default.id
  priority           = 1000
  destination_ranges = ["0.0.0.0/0"]
  target_tags        = ["ssh"] # 与实例标签匹配
}

3. 入向ICMP规则未关联实例

现有allow-icmp规则的target_tags为["icmp"],但实例标签仅包含["ssh"],导致规则无法作用于实例。可通过以下两种方式修复:

方式一:给实例添加icmp标签

resource "google_compute_instance" "manager1" {
  # ... 其他配置
  tags = ["ssh", "icmp"]
}

resource "google_compute_instance" "manager2" {
  # ... 其他配置
  tags = ["ssh", "icmp"]
}

方式二:修改防火墙规则的target_tags

resource "google_compute_firewall" "icmp" {
  # ... 其他配置
  target_tags = ["ssh"]
}

4. 可选:开启子网私有Google访问

若需确保实例能正常访问Google服务(如DNS、Cloud Storage),可开启子网的私有Google访问:

resource "google_compute_subnetwork" "default" {
  name                   = "manager-subnet"
  ip_cidr_range          = "10.10.10.0/24"
  region                 = "us-west1"
  network                = google_compute_network.default.id
  private_ip_google_access = true # 开启私有Google访问
}

内容的提问来源于stack exchange,提问作者Klevin Kona

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 02:45:40