【问题标题】:How to connect a Spring Boot service from Google Cloud Run to SQL cloud instance?如何将 Spring Boot 服务从 Google Cloud Run 连接到 SQL 云实例?
【发布时间】:2021-10-04 02:02:52
【问题描述】:

我创建了一个 SQL 实例。这是工作。 然后,我将我的 Spring Boot 应用程序的 docker 镜像上传到了 Container Registry。

我的目标是在 Google Cloud Run 上运行该应用程序,但为了使其工作,它必须连接到数据库。因此,在创建服务时,我给它图像并传递环境变量:

  • spring.datasource.url(这里我作为值传递 - jdbc:mysql://(sql实例的公共IP地址)/(数据库名称)?useSSL=false
  • spring.datasource.username ...
  • spring.datasource.password ...

另外,我在高级设置中连接到云 SQL 实例。

但是,当我部署它时,它失败了。 spring 应用程序正在启动,但随后出现通信链接故障。我想它没有找到数据库,或者它必须对权限做一些事情。

我是 Google Cloud 的新手,希望得到一些帮助。我怎么能解决这个问题?还是我做错了什么?

【问题讨论】:

  • 您是否在 Cloud SQL 实例上配置了授权网络?如果是这样,你配置了什么?

标签: java sql spring-boot google-cloud-platform google-cloud-run


【解决方案1】:

Cloud SQL 的 MySQL 实例可以有一个公共 IP 和一个私有 IP。

要从使用公共 IP 的实例连接 Cloud Run 应用程序,需要通过 Unix 套接字使用 Cloud SQL Auth Proxy。可以关注this document了解步骤。

要使用私有 IP 从实例连接 Cloud Run 应用程序,需要使用无服务器 VPC 访问连接器。您关注this document了解步骤。

您已经为 Spring Boot 应用程序创建了一个镜像并将其部署在 Cloud Run 中并传递了环境变量。在 spring.datasource.url 中,您直接使用了公共 IP,这将无法作为 the recommended way 使用公共 IP 进行连接,而是通过 Unix 套接字路径使用 CloudSQL Auth Proxy

我建议您使用提到的 jdbcUrl here 作为 spring.datasource.url,看起来像这样-

jdbc:mysql:///<DATABASE_NAME>?cloudSqlInstance=<INSTANCE_CONNECTION_NAME>&socketFactory=com.google.cloud.sql.mysql.SocketFactory&user=<MYSQL_USER_NAME>&password=<MYSQL_USER_PASSWORD>&useSSL=false

在哪里,

<DATABASE_NAME> = Your database name in the MySQL instance

<INSTANCE_CONNECTION_NAME> = Connection name of the MySQL instance of Cloud SQL (can be found in the instance overview page in the Cloud Console) which follows a certain pattern i.e. <project-id : region : instance-id>.

<MYSQL_USER_NAME> = Username for the MySQL instance

<MYSQL_USER_PASSWORD> = Password for the above username

使用上述spring.datasource.url 时,您不必分别指定spring.database.usernamespring.datasource.password 属性,因为网址中都提到了这两个属性。

【讨论】:

    【解决方案2】:

    默认情况下,无服务器(如 Cloud Run)无权访问其他资源。

    您必须配置 Serverless VPC Access 才能在专用网络中使用数据库、谷歌服务或其他服务。

    然后您必须将无服务器 VPC 访问分配给您的云运行服务。

    【讨论】:

      猜你喜欢
      • 2021-12-25
      • 2021-02-12
      • 2019-10-28
      • 2020-11-20
      • 2019-09-16
      • 2015-05-14
      • 1970-01-01
      • 2021-07-18
      • 2020-08-31
      相关资源
      最近更新 更多