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

PostgreSQL 14远程连接超时故障排查求助

PostgreSQL 14远程连接超时问题排查求助

问题现象

远程连接PostgreSQL时出现超时错误:

~$ psql -U postgres -h remote.server.address -p 5432 datadb
psql: error: connection to server at remote.server.address, port 5432 
failed: 
Connection timed out
Is the server running on that host and accepting TCP/IP connections?

本地连接数据库正常,且该服务几天前可正常远程访问。

已完成的检查

  1. 服务状态确认

    $ sudo systemctl status 'postgresql*'
    ● postgresql@14-main.service - PostgreSQL Cluster 14-main
         Loaded: loaded (/lib/systemd/system/postgresql@.service; enabled-runtime; vendor preset: enabled)
         Active: active (running) since Wed 2023-06-07 07:11:15 UTC; 14s ago
        Process: 3614 ExecStart=/usr/bin/pg_ctlcluster --skip-systemctl-redirect 14-main start (code=exited, status=0/SUCCESS)
       Main PID: 3619 (postgres)
          Tasks: 7 (limit: 4694)
         Memory: 18.1M
            CPU: 164ms
    
  2. 端口监听状态

    $ sudo lsof -i -n -P | grep -E 'postgres.*LISTEN.*' | less
    postgres  2775        postgres    5u  IPv4  30639      0t0  TCP *:5432 (LISTEN)
    postgres  2775        postgres    6u  IPv6  30640      0t0  TCP *:5432 (LISTEN)
    
  3. PostgreSQL配置

    • postgresql.conf关键配置:
      listen_addresses = '*'                  # what IP address(es) to listen on;
      port = 5432                             # (change requires restart)
      max_connections = 100                   # (change requires restart)
      
    • pg_hba.conf远程访问规则:
      # IPv4 remote connections for the tutorial:
      host    all             all             0.0.0.0/0               md5
      
  4. 防火墙规则尝试
    已添加UFW规则,但问题未解决:

    $ sudo ufw allow 5432/tcp
    Skipping adding existing rule
    Skipping adding existing rule (v6)
    

进一步排查建议

  • 验证网络连通性

    • 执行ping remote.server.address确认服务器地址可解析且网络可达;若ping不通,优先排查DNS解析或基础网络链路问题
    • 用nc -zv remote.server.address 5432测试端口连通性,判断是网络层阻断还是应用层问题
  • 检查云服务商安全组
    若使用云实例,登录云控制台检查安全组的入方向规则,确保允许5432端口的TCP流量从客户端IP(或按需开放的IP范围)进入,部分云服务商的默认安全组会阻断非常见端口

  • 确认服务器公网IP状态
    检查服务器公网IP是否发生变更(部分云实例重启后可能自动更换IP),对比连接时使用的remote.server.address是否对应当前有效IP

  • 验证PostgreSQL生效配置

    • 登录本地数据库执行SHOW listen_addresses;和SHOW port;,确认实际生效的配置与修改的文件一致(避免修改了错误路径的配置文件)
    • 执行SELECT * FROM pg_hba_file_rules;查看pg_hba规则的加载状态,确认远程访问规则已生效
  • 排查服务器端深层防火墙

    • 执行sudo iptables -L -n -v查看是否存在iptables规则拦截5432端口;若有,可临时执行sudo iptables -F清空规则测试连接(测试后需恢复规则)
    • 检查是否有其他安全软件(如fail2ban)自动封禁了客户端IP
  • 排查客户端网络限制
    尝试切换客户端网络(如手机热点)测试,排除客户端所在网络的防火墙、代理或VPN对5432端口的拦截;同时检查客户端hosts文件是否存在错误的地址解析


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 19:39:52