云 运行:<Cloud SQL instance IP adress>:3306: 连接:连接超时

Cloud Run:<Cloud SQL instance IP adress> :3306: connect: connection timed out

我想在 Cloud 运行 应用程序中连接 Cloud SQL。我用的是高朗。这是围绕 sql 连接设置的代码。

func getEnv(key, def string) string {
    v := os.Getenv(key)
    if v == "" {
        return def
    }
    return v
}
        DB: DB{
            User:     getEnv("DB_USER", "<user name>"),
            Pass:     getEnv("DB_PASS", "<password>"),
            Host:     getEnv("DB_HOST", "0.0.0.0"),
            Port:     getEnv("DB_PORT", "3306"),
            Database: getEnv("DB_DATABASE", "<database name>"),
        },
    dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=true",
        config.DB.User, config.DB.Pass, config.DB.Host, config.DB.Port, config.DB.Database)

    db, err := gorm.Open("mysql", dsn)

我在云 运行 设置控制台设置了环境变量。 delpoy应用后,云运行控制台显示Cloud Run error: Container failed to start. Failed to start and then listen on the port defined by the PORT environment variable. Logs for this revision might contain more information.dial tcp <Cloud SQL Private IP> :3306: connect: connection timed out不知SQL连接有误...

你没有在你的问题中提到“VPC”这个词,所以我假设你没有使用它。

Cloud 运行 无法直接连接到 Cloud SQL 实例的私有 IP。您需要 configure a Serverless VPC Access Connector 并在部署云 运行 应用程序时指定它。

云 运行 容器默认情况下不是 VPC 的一部分,因此除非您这样做,否则它们将无法访问专用网络。

有多种方法可以将您的 Cloud SQL 数据库连接到 Cloud 运行。如果是MySQL,最简单的方法就是按照official documentation

如果要使用TCP连接的IP,首先不能使用0.0.0.0作为IP。

  • 使用云 SQL public IP(为此你必须在你的云 SQL 实例上授权 0.0.0.0/0 网络范围,绝对不推荐)
  • 插上你的Cloud SQL to your VPC。并且,如 Ahmet 所述,使用无服务器 VPC 连接器将 link Cloud 运行 与您的 VPC 连接起来。然后在您的代码中添加您的 Cloud SQL 的私有 IP。