DEBUG.WIKI
IPPeak:从目标地区访问网页,住宅代理、SEO 监测、广告验证
阿里云;从建站到云上业务;云服务器 · 数据库 · 对象存储;查看产品 →
搬瓦工;先看线路,再选 VPS;CN2 GIA · 对应线路套餐;查看线路 →

解决 PostgreSQL 报错 could not connect to server: Connection refused 及 pg_hba 排查

排查 PostgreSQL 客户端连接报错 could not connect to server: Connection refused,解决 listen_addresses 与 pg_hba.conf 鉴权限制。

问题现象

在应用客户端或使用 psql 尝试连接远程 PostgreSQL 实例时,连接失败:

psql: error: could not connect to server: could not connect to server: Connection refused
	Is the server running on host "192.168.1.100" and accepting
	TCP/IP connections on port 5432?

或者在连接被服务端接受后,鉴权阶段被拒绝:

FATAL:  no pg_hba.conf entry for host "192.168.1.50", user "app", database "production", no encryption

触发根因

PostgreSQL 在网络访问控制上有两道关键防线:

  1. 网络监听限制(Network Binding):postgresql.conf 中的 listen_addresses 默认仅为 'localhost'。此时数据库只监听 127.0.0.1:5432,任何来自外部网络接口的 TCP 连接在网络层直接被拒绝(Connection refused)。
  2. 主机访问鉴权控制(Host-Based Authentication):pg_hba.conf 严格控制了哪些客户端 IP 能够以何种身份和认证方法访问特定的数据库。若缺少匹配行,服务端会返回 FATAL: no pg_hba.conf entry。

解决步骤

1. 检查服务监听地址与本地端口状态

在服务端执行:

sudo ss -tulpn | grep 5432

若显示 127.0.0.1:5432,说明未监听公网/内网网卡。编辑 postgresql.conf:

# 允许监听所有网络接口,或指定内网 IP
listen_addresses = '*'
port = 5432

2. 在 pg_hba.conf 中追加客户端授权规则

编辑 pg_hba.conf(通常位于数据目录或 /etc/postgresql/XX/main/):

# TYPE  DATABASE        USER            ADDRESS                 METHOD
# 允许特定子网通过 scram-sha-256 密码鉴权
host    production      app             192.168.1.0/24          scram-sha-256

3. 重启或重载服务

修改 listen_addresses 需要重启服务:

sudo systemctl restart postgresql

如果仅仅是修改了 pg_hba.conf,只需重载即可生效:

sudo systemctl reload postgresql

验证确认

从客户端再次连接:

psql -h 192.168.1.100 -U app -d production

输入密码后成功进入交互式 Shell,连接恢复正常。