繁体   English   中英

GCP Cloud Functions 使用私有 IP 连接到云 sql

[英]GCP Cloud Functions connecting to cloud sql with private IP

我正在按照此示例建立从 Cloud Function 到 Postgres Cloud SQL 的连接: https : //cloud.google.com/functions/docs/sql

当我使用公共 IP 创建测试 Cloud SQL 实例并触发云函数时,它会连接到云 SQL 实例并返回一些内容。 出于安全原因,我不能保留公共 IP,因此当我在云 SQL 实例上选择私有 IP 时,我得到:

Error: function crashed. Details:
could not connect to server: Connection refused
    Is the server running locally and accepting
    connections on Unix domain socket "/cloudsql/cloud-sql-test-250613:us-central1:myinstance-2/.s.PGSQL.5432"?

我无法从文档中获得云函数和云 sql 实例之间的契约是什么。 如果我们使用 unix 域套接字,我应该关心 IP 吗? 它是公共的还是私人的,这很重要吗? 如果确实重要,我是否必须完成设置私有 IP 基础设施的所有过程? 我需要无服务器 VPC 吗?

通过这样做,我设法实现了 Cloud Function 和 Cloud SQL 私有实例之间的连接。

如果您禁用公共 IP,这似乎很重要,每当我禁用公共 IP 时,我一直收到 ERR CONN REFUSED,这似乎是您的情况,让您的 Cloud SQL 实例仅使用私有 IP,我认为您必须使用无服务器专有网络。

这是我建议您尝试的方法:

确保您的所有基础架构都在同一区域(Cloud SQL、Cloud Function、VPC 连接器)

请采取以下步骤:

  1. 将 Cloud SQL 实例设置为仅限专用连接。 (云 SQL 实例 > 连接)

  2. 确保您的私有 CloudSQL 实例位于所需的“关联网络”(VPC) 上。

  3. 在您的 Cloud SQL 实例所在的 VPC 网络上创建一个 VPC 连接器。 (与 MySql 实例关联的那个)

要创建连接器,请转到:VPC 网络 > VPC 无服务器访问 > 创建连接器

在 VPC 网络 > [您的 VPC] > VPC 网络对等互连中,您可以检查与 Cloud SQL 实例的连接是否正确。

  1. 使用所需语言的代码创建云函数。 (您可以使用文档中的示例进行测试。)

创建 Cloud Function 时,请确保将其设置在同一区域中,同时将您创建的 VPC 连接器添加到 Cloud Function 中的“出口设置”选项。

如果您尝试通过 GCP Console 创建 VPC 连接器,您将只能选择 1 个区域。 但是,如果您使用云外壳,则可以定义其他区域。 您可以使用此命令并在这些区域中进行尝试。

gcloud beta compute networks vpc-access connectors create [CONNECTOR_NAME] \ 
--network [VPC_NETWORK] \ 
--region [REGION] \ 
--range [IP_RANGE]

领域:

us-central1, us-east1, europe-west1

如果这对你有用,请告诉我。

更新:

再次你好 alobodzk,

尝试在 Python 中创建您的 Cloud Function(一旦确保前面的所有步骤都正常)。

试试这个代码:

Cloud Function index.js(用您自己的凭据替换所有连接器数据)

import mysql.connector
from mysql.connector import Error


def mysql_demo(request):
    import mysql.connector
    from mysql.connector import Error
    try:
        connection = mysql.connector.connect(host='CloudSQL Instance Private IP', database='Database Name, user='UserName', password='Password')
        if connection.is_connected():
            db_Info = connection.get_server_info()
            print("Connected to MySQL database... MySQL Server version on ",db_Info)
            cursor = connection.cursor()
            cursor.execute("select database();")
            record = cursor.fetchone()
            print ("Your connected to - ", record)
    except Error as e :
        print ("Error while connecting to MySQL", e)
    finally:
        #closing database connection.
        if(connection.is_connected()):
            cursor.close()
            connection.close()
            print("MySQL connection is closed")
# [END functions_sql_mysql]

云功能要求.txt

psycopg2==2.7.7
PyMySQL==0.9.3
mysql-connector-python

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM