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

Cloud Function通过Serverless VPC Access路由全部出口流量后仍可访问Google APIs的异常问题

问题原因分析

你遇到的这个情况其实是GCP的预期行为,核心在于Google Cloud官方客户端库和Google APIs的特殊访问机制,我来给你拆解清楚:

1. Google Cloud客户端库的内部通信逻辑

你用的@google-cloud/bigquery是GCP官方提供的SDK,它和普通的HTTP请求工具(比如node-fetch)的工作方式完全不同:

  • 这类SDK不会通过公网HTTP请求访问BigQuery服务,而是会利用Google Cloud内部的专用服务通道(基于Service Networking)直接和BigQuery的后端通信。
  • 这种通信完全绕开了公网,也不需要依赖你VPC里的互联网网关或者Cloud NAT,所以即使你把Cloud Function的所有出口流量都路由到Serverless VPC Access,它依然能正常建立连接。

2. Google APIs的例外规则

根据GCP的官方规则,当你配置Cloud Function将所有出口流量路由至Serverless VPC Access时:

  • 非Google的公网API会被限制访问(因为没有Cloud NAT提供公网出口),这也是你用node-fetch访问第三方API失败的原因,符合预期。
  • 但Google自家的APIs(包括BigQuery、Cloud Storage等)是例外,它们不受这个路由限制,因为GCP为这些服务提供了内部访问路径,不需要走公网出口就能完成通信。

3. 额外验证点(可选)

如果你想要强制让BigQuery通过VPC私有访问,可以配置BigQuery的私有服务访问(Private Service Access),此时客户端库会通过VPC的内部IP地址访问BigQuery服务。不过即使不做这个配置,默认的SDK行为依然会使用内部通道,所以不会影响访问。

你的测试代码参考

访问BigQuery的Cloud Function(预期失败但实际正常)

const {BigQuery} = require('@google-cloud/bigquery');
const bigquery = new BigQuery();
exports.getCountries = async (req, res) => {
  const query = "SELECT DISTINCT country_name FROM `bigquery-358204.covid_19_data.covid19_open_data` ORDER BY country_name;";
  const options = {
    query: query,
    location: 'US',
  };
  // Run the query as a job
  const [job] = await bigquery.createQueryJob(options);
  console.log(`Job ${job.id} started.`);
  // Wait for the query to finish
  const [rows] = await job.getQueryResults();
  let message = JSON.stringify(rows);
  res.status(200).send(message);
};

访问非Google API的Cloud Function(符合预期访问失败)

const fetch = require('node-fetch')
exports.helloWorld = async (req, res) => {
  let resp = await fetch('https://www.7timer.info/bin/astro.php?lon=113.2&lat=23.1&ac=0&unit=metric&output=json&tzshift=0');
  let body = await resp.json()
  res.status(200).send(body)
};

内容的提问来源于stack exchange,提问作者Ajith CR

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 18:28:11