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

Composer2升级后无法通过Cloud SQL Proxy连接PostgreSQL的咨询

Composer 2(Airflow 2.5.3)Cloud SQL Proxy连接问题排查及连接方式对比

问题背景

近期从Composer 1升级至Composer 2(版本2.6.2,对应Airflow 2.5.3),此前使用BaseHook搭配Cloud SQL Proxy连接PostgreSQL Cloud SQL,因Airflow 2中BaseHook已被弃用,改为使用PostgresHook。目前无法通过Cloud SQL Proxy建立连接;直接使用Cloud SQL IP可连接但速度极慢,需排查无法连接的原因,并对比两种连接方式的优势。

代码实现

原代码(基于BaseHook)

from airflow.hooks.base_hook import BaseHook

def sql_alchemy_engine(conn_id):
    return BaseHook.get_connection(conn_id).get_hook().get_sqlalchemy_engine(engine_kwargs={'echo': False})

修改后代码(基于PostgresHook)

from airflow.hooks.postgres_hook import PostgresHook

def sql_alchemy_engine(conn_id):
    postgres_hook = PostgresHook(conn_id)
    engine = postgres_hook.get_sqlalchemy_engine()
    return engine

Cloud SQL Proxy配置文件

test_edl-cloud-sql-proxy.yml(Deployment配置)

apiVersion: apps/v1
kind: Deployment
metadata:
  name: edl-cloud-sql-proxy
  namespace: default
spec:
  selector:
    matchLabels:
      app: edl-cloud-sql-proxy
  template:
    metadata:
      labels:
        app: edl-cloud-sql-proxy
    spec:
      containers:
      - command:
        - /cloud_sql_proxy
        - -dir=/cloudsql
        - -instances=test-project:europe-west1-d:cloud-sql-name=tcp:0.0.0.0:5432
        - -ip_address_types=PRIVATE
        - term_timeout=10s
        image: gcr.io/cloudsql-docker/gce-proxy:1.14
        imagePullPolicy: IfNotPresent
        lifecycle:
          preStop:
            exec:
              command:
              - sleep
              - "10"
        name: edl-cloud-sql-proxy
        ports:
        - containerPort: 5432
          name: port-postgres
          protocol: TCP
        resources: {}
        securityContext:
          allowPrivilegeEscalation: false
          runAsUser: 2
        terminationMessagePath: /dev/termination-log
        terminationMessagePolicy: File
        volumeMounts:
        - mountPath: /cloudsql
          name: cloudsql
      dnsPolicy: ClusterFirst
      restartPolicy: Always
      schedulerName: default-scheduler
      securityContext: {}
      terminationGracePeriodSeconds: 30
      volumes:
      - emptyDir: {}
        name: cloudsql

test_mapp-sqlproxy-service.yml(Service配置)

apiVersion: v1
kind: Service
metadata:
  name: mapp-sqlproxy-service
spec:
  type: ClusterIP
  selector:
    app: edl-cloud-sql-proxy
  ports:
  - port: 5432
    protocol: TCP
    targetPort: port-postgres

执行命令及错误信息

kubectl apply -f test_edl-cloud-sql-proxy.yml
kubectl apply -f test_mapp-sqlproxy-service.yml

xyz@test-cloudbuild-bastion:~$ kubectl get services --all-namespaces
# 服务列表省略
xyz@test-cloudbuild-bastion:~$ psql -h mapp-sqlproxy-service.default.svc.cluster.local --user seed-cloudbuild
psql: could not translate host name "mapp-sqlproxy-service.default.svc.cluster.local" to address: Temporary failure in name resolution

DAG连接错误日志

File "/opt/python3.8/lib/python3.8/site-packages/psycopg2/__init__.py", line 122, in connect
    conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) server closed the connection unexpectedly
    This probably means the server terminated abnormally
    before or while processing the request.

无法连接的原因排查

  1. K8s服务域名解析失败

    • 确认mapp-sqlproxy-service在default namespace的运行状态:执行kubectl get svc -n default查看服务是否存在,kubectl describe svc mapp-sqlproxy-service -n default检查Endpoints字段是否关联正常运行的Proxy Pod
    • 跳过域名解析,直接用服务ClusterIP测试:先通过kubectl get svc mapp-sqlproxy-service -n default获取ClusterIP,再执行psql -h <cluster-ip> --user seed-cloudbuild验证连接
    • 检查bastion主机所在网络是否能访问K8s集群的DNS服务,确保内部域名解析正常
  2. Cloud SQL Proxy Pod运行异常

    • 执行kubectl get pods -n default查看Proxy Pod状态,确认是否处于Running状态、有无重启记录
    • 查看Pod日志:kubectl logs <proxy-pod-name> -n default,检查是否有权限错误、实例地址错误等信息
    • 当前使用的Proxy版本1.14过于老旧,建议升级至最新稳定版(如2.x系列),旧版本可能存在兼容性缺陷
  3. 网络与权限配置问题

    • 确认Cloud SQL实例的私有网络与K8s集群在同一VPC或已配置VPC peering,确保Proxy Pod能访问Cloud SQL私有IP
    • 检查Proxy Pod使用的ServiceAccount权限:当前未指定ServiceAccount,默认使用Node的ServiceAccount,需确认该账号是否拥有Cloud SQL Client角色权限
    • 验证Proxy启动命令中的实例地址格式:确认test-project:europe-west1-d:cloud-sql-name=tcp:0.0.0.0:5432的项目ID、区域、实例名称无误
  4. Airflow连接配置问题

    • 检查Airflow中PostgreSQL连接配置,确认主机地址为mapp-sqlproxy-service.default.svc.cluster.local或正确ClusterIP,端口为5432
    • 确认连接配置的用户名、密码与Cloud SQL实例账号信息匹配

两种连接方式优势对比

Cloud SQL Proxy连接

  • 安全性高:无需暴露Cloud SQL公网IP,连接通过加密通道传输;依赖IAM权限控制访问,无需维护IP白名单,适配动态环境
  • 网络性能优:Proxy部署在K8s集群内,使用Cloud SQL私有IP连接,同VPC内延迟极低,速度远快于公网IP连接
  • 运维便捷:Proxy组件可通过K8s实现自动重启、故障转移,无需手动更新白名单,适配Airflow节点扩缩容

直接使用Cloud SQL IP连接

  • 架构简单:无需额外部署Proxy组件,减少系统依赖与运维复杂度
  • 无Proxy单点风险:避免Proxy组件故障导致的批量连接中断
  • 劣势明显:
    • 公网IP连接需维护IP白名单,动态环境下更新频繁,且公网传输延迟高、速度慢
    • 私有IP连接需确保Airflow节点与Cloud SQL在同一VPC或已配置peering,扩展性差,仍存在IP暴露的安全风险

内容的提问来源于stack exchange,提问作者Vikrant Singh Rana

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 23:22:10