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

Python连接Cloud SQL MySQL失败问题求助

问题

尝试用Python代码连接Cloud SQL的MySQL实例,已创建个人用户,使用实例公网IP作为主机地址,出现以下错误:

ERROR:google.cloud.sql.connector.instance:['project:location:instance']: An error occurred while performing refresh. Scheduling another refresh attempt immediately
Traceback (most recent call last):
  File "/usr/local/lib/python3.10/dist-packages/google/auth/compute_engine/credentials.py", line 126, in refresh
    self._retrieve_info(request)
  File "/usr/local/lib/python3.10/dist-packages/google/auth/compute_engine/credentials.py", line 99, in _retrieve_info
    info = _metadata.get_service_account_info(
  File "/usr/local/lib/python3.10/dist-packages/google/auth/compute_engine/_metadata.py", line 318, in get_service_account_info
    return get(request, path, params={"recursive": "true"})
  File "/usr/local/lib/python3.10/dist-packages/google/auth/compute_engine/_metadata.py", line 243, in get
    raise exceptions.TransportError(
google.auth.exceptions.TransportError: ("Failed to retrieve http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/?recursive=true from the Google Compute Engine metadata service. Status: 404 Response:
b''", <google.auth.transport.requests._Response object at 0x7d0011838310>)


MySQLInterfaceError                       Traceback (most recent call last)
/usr/local/lib/python3.10/dist-packages/mysql/connector/connection_cext.py in _open_connection(self)
    326         try:
--> 327             self._cmysql.connect(**cnx_kwargs)
    328             self._cmysql.converter_str_fallback = self._converter_str_fallback

MySQLInterfaceError: Can't connect to MySQL server on 'my_public_ip' (110)

The above exception was the direct cause of the following exception:

DatabaseError                             Traceback (most recent call last)
4 frames
/usr/local/lib/python3.10/dist-packages/mysql/connector/connection_cext.py in _open_connection(self)
    330                 self.converter.str_fallback = self._converter_str_fallback
    331         except MySQLInterfaceError as err:
--> 332             raise get_mysql_exception(
    333                 msg=err.msg, errno=err.errno, sqlstate=err.sqlstate
    334             ) from err

DatabaseError: 2003 (HY000): Can't connect to MySQL server on 'my_public_ip' (110)

使用的Python代码:

#### Establish Connetion ####

cnx = mysql.connector.connect(user='my.user', password='my_password', host='public_ip_address', 
                              database='plus_data')

cursor = cnx.cursor()

#### Connetion Established ####

#### Execute query ####

query1 = ("select 1")
cursor.execute(query1)

已尝试创建新用户、使用私网IP,问题仍未解决,请求排查。

排查与解决方案
  • 公网连接防火墙配置检查

    1. 登录Cloud SQL控制台,进入目标MySQL实例的「连接」页面
    2. 确认「公网IP」已启用,且「授权网络」列表中添加了当前运行Python代码的机器的公网IP(需带/32后缀,例如192.168.1.1/32)
    3. 若代码运行在GCE等云服务器上,检查服务器所在VPC的出站防火墙规则,确认允许访问3306端口
  • 用户权限验证

    1. 登录Cloud SQL的MySQL实例,执行以下SQL查看用户权限范围:
      SELECT host, user FROM mysql.user WHERE user = 'my.user';
      
      确保用户的host字段为%(允许任意IP连接)或当前机器的公网IP,而非仅localhost或私网IP
    2. 确认密码输入正确,避免特殊字符转义问题,可先用纯文本密码测试
  • 网络连通性测试
    在运行Python代码的机器上,执行以下命令测试端口连通性:

    telnet my_public_ip 3306
    # 或使用nc命令
    nc -zv my_public_ip 3306
    

    若连接超时,说明网络层面存在阻断,回到防火墙配置检查;若能连通,再排查代码或MySQL配置

  • 元数据服务错误处理
    错误中的google.auth.exceptions.TransportError是因为代码环境不在GCP内部(如本地机器),可通过以下方式处理:

    1. 在代码开头添加环境变量设置,禁用自动GCP凭证加载:
      import os
      os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = ''
      
    2. 若未使用google.cloud.sql.connector,可卸载或移除相关依赖

内容的提问来源于stack exchange,提问作者Alessandra Ulinick

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 16:30:02