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

使用pg_isready测试PostgreSQL本地别名连接失败问题排查

问题描述

我正在编写脚本以检查PostgreSQL数据库服务器是否正常运行。已在/etc/hosts中为localhost添加别名db_host,本地执行ping命令可正常解析:

ping db_host
PING db_host (127.0.1.1) 56(84) bytes of data.
64 bytes from <machine name> (127.0.1.1): icmp_seq=1 ttl=64 time=0.050 ms

PostgreSQL提供的服务器就绪检查工具pg_isready,使用localhost作为主机参数时显示服务器正常接受连接:

pg_isready -h localhost
localhost:5432 - accepting connections

但使用别名db_host作为主机参数时测试失败:

pg_isready -h db_host
db_host:5432 - no response

根据PostgreSQL官方文档,此操作应可行,请问问题出在哪里?

可能的原因及解决方法
  • PostgreSQL监听地址限制
    PostgreSQL默认可能仅监听localhost(对应127.0.0.1),未监听db_host解析到的127.0.1.1。检查postgresql.conf中的listen_addresses配置:

    grep listen_addresses /etc/postgresql/<版本号>/main/postgresql.conf
    

    若值为'localhost',需修改为包含127.0.1.1或监听所有地址:

    listen_addresses = 'localhost,127.0.1.1'
    # 或监听所有地址
    listen_addresses = '*'
    

    修改后重启PostgreSQL服务生效。

  • 主机名解析指向差异
    localhost通常解析到127.0.0.1,而你的db_host指向127.0.1.1,两者虽同属环回地址,但PostgreSQL若仅绑定127.0.0.1则无法响应127.0.1.1的请求。可修改/etc/hosts,将db_host指向127.0.0.1:

    127.0.0.1   localhost db_host
    
  • pg_hba.conf访问控制限制
    检查pg_hba.conf,确认是否允许127.0.1.1地址的连接。需添加类似规则:

    host    all             all             127.0.1.1/32            scram-sha-256
    

    或允许所有环回地址:

    host    all             all             127.0.0.0/8            scram-sha-256
    

    修改后执行pg_ctl reload重新加载配置,或重启服务。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 16:12:38