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

升级Postgres 14后Kubernetes集群内容器无法连接数据库求助

排查Postgres 14升级后K8s内部连接拒绝问题

以下是针对该问题的具体排查步骤:

  • 检查Postgres监听地址配置
    Postgres 11到14的默认配置可能存在差异,新版本可能默认仅监听localhost,导致仅容器内部可访问,K8s集群内其他Pod无法通过Pod IP连接。

    1. 进入Postgres容器:kubectl exec -it <postgres-pod-name> -- bash
    2. 查看当前监听配置:psql -U <db-username> -c "SHOW listen_addresses;"
    3. 若结果为localhost,修改postgresql.conf中的配置:将listen_addresses = 'localhost'改为listen_addresses = '*'
    4. 重启Postgres Pod生效:kubectl delete pod <postgres-pod-name>(假设使用Deployment管理,会自动重建)
  • 验证K8s Service与Pod的端口映射
    确认Service的端口配置与Postgres容器暴露的端口一致:

    1. 查看Service详情:kubectl describe service <postgres-service-name>
      检查Spec.Ports中的TargetPort是否等于Postgres容器使用的端口(默认5432)
    2. 查看Pod详情:kubectl describe pod <postgres-pod-name>
      确认Containers.Ports中的ContainerPort为5432(或自定义端口)
  • 检查Pod内部端口监听状态
    确认Postgres进程实际监听的端口和地址:
    进入Postgres容器执行:ss -tulpn | grep 5432
    若输出仅显示127.0.0.1:5432,说明确实存在监听地址限制,需要调整listen_addresses配置。

  • 排查K8s网络策略
    若集群中存在NetworkPolicy,可能阻止了其他Pod访问Postgres服务:

    1. 查看所有网络策略:kubectl get networkpolicy --all-namespaces
    2. 检查针对Postgres所在命名空间的策略,确认是否允许客户端Pod所在IP段或命名空间访问5432端口。
  • 验证pg_hba.conf认证规则
    即使监听地址正确,pg_hba.conf可能未允许K8s集群内部IP段访问:

    1. 进入Postgres容器,查看pg_hba.conf内容:cat /var/lib/postgresql/data/pg_hba.conf
    2. 添加允许集群Pod IP段的规则,例如:
      host  all  all  <集群Pod CIDR>/24  scram-sha-256
      
      (替换<集群Pod CIDR>为实际的K8s Pod网段,可通过kubectl get nodes -o jsonpath='{.items[*].spec.podCIDR}'查看)
    3. 重启Postgres Pod使配置生效。
  • 检查Service端点状态
    确认Service已正确关联到Postgres Pod:
    执行kubectl get endpoints <postgres-service-name>,查看ENDPOINTS字段是否包含Postgres Pod的IP和5432端口。若为空,检查Service的标签选择器是否与Pod的标签匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 15:43:29