Cloud 运行 和 Cloud SQL 之间的连接(内部 IP)

Connectivity between Cloud Run and Cloud SQL (Internal IP)

我已经按照 Google 提供的 Cloud Foundation Toolkit using the Terraform modules 在 GCP 中创建了我的组织基础设施。

以下 table 列出了所有环境的 IP 范围:

现在我正在部署我的应用程序,该应用程序基本上由云 运行 服务和云 SQL (Postgres) 实例组成。 Cloud SQL 实例是使用“未分配”IP 范围内的私有 IP 创建的,该 IP 范围是为对等服务(例如 Cloud SQL)保留的。

为了在 Cloud 运行 和 Cloud SQL 之间建立连接,我还创建了无服务器 VPC 连接器(IP 范围 10.1.0.16/28)并配置了 Cloud SQL代理。

当我尝试从云 运行 服务连接到数据库时,我在 ~10 秒后收到此错误:

CloudSQL connection failed. Please see https://cloud.google.com/sql/docs/mysql/connect-run for additional details: Post "https://www.googleapis.com/sql/v1beta4/projects/[my-project]/instances/platform-db/createEphemeral?alt=json&prettyPrint=false": context deadline exceeded

我已经为默认 Cloud 运行 SA 和宿主项目中的应用程序使用的 SA 授予了 roles/vpcaccess.user

我已为服务项目中的两个 SA 授予 roles/compute.networkUser。我还为两个 SA 授予 roles/cloudsql.client

我在服务项目中启用了servicenetworking.googleapis.comvpcaccess.googleapis.com

我 运行 没有想法,我无法弄清楚问题是什么。

当 Cloud 运行 尝试向 Cloud SQL API 创建 POST 请求时,这似乎是一个超时错误。所以看起来 VPC 连接器 (10.1.0.16/28) 无法连接到云 SQL 实例 (10.0.80.0/20)。

有没有人以前遇到过这个问题?

当您在 Cloud 运行(以及 App Engine 和 Cloud Function)中使用 Cloud SQL 内置连接时,会创建类似于 Cloud SQL 代理的连接。这种连接 在云 SQL public IP 上实现,即使您有无服务器 VPC 连接器并且您的数据库可通过 VPC 访问。

如果您在 Cloud SQL 上只有私有 IP,则需要使用私有 IP 访问数据库,而不是内置的 Cloud SQL 连接器。 the documentation

中有更多详细信息

我也写了an article on this

如果您使用的是私有 IP,则需要检查 docker 桥接网络的 IP 范围。 documentation 是这样说的:

If a client cannot connect to the Cloud SQL instance using private IP, check to see if the client is using any IP in the range 172.17.0.0/16. Connections fail from any IP within the 172.17.0.0/16 range to Cloud SQL instances using private IP. Similarly, Cloud SQL instances created with an IP in that range are unreachable. This range is reserved for the docker bridge network.

要解决您遇到的一些问题,请遵循文档 here 和 post 您收到的任何错误消息,例如,您可以尝试:

Try the gcloud sql connect command to connect to your instance. This command authorizes your IP address for a short time. You can run this command in an environment with Cloud SDK and mysql client installed. You can also run this command in Cloud Shell, which is available in the Google Cloud Console and has Cloud SDK and the mysql client pre-installed.

Temporarily allow all IP addresses to connect to an instance. For IPv4 authorize 0.0.0.0/0 (for IPv6, authorize ::/0. After you have tested this, please make sure you remove it again as it opens up to the world!

您在使用 connection pools 吗?

如果没有,我会创建一个连接缓存,这样当您的应用程序需要 link 到数据库时,它可以从池中获取一个临时连接。一旦应用程序完成其操作,连接 returns 再次连接到池以供以后使用。为了使其正常工作,连接需要 open and closed efficiently 并且不浪费任何资源。