postgres-connection-failed

PostgreSQL 连接失败的定位与修复

现象

客户端报 could not connect to server、FATAL: password authentication failed、no pg_hba.conf entry、too many connections 或 SSL error。

快速定位

pg_isready -h <host> -p 5432
ss -lntp | grep 5432
psql -h <host> -p 5432 -U <user> -d <db> -c 'SELECT 1'
psql -c 'SHOW max_connections'
psql -c "SELECT state, count(*) FROM pg_stat_activity GROUP BY state"
psql -c 'SHOW ssl'

服务端:

journalctl -u postgresql --since '30 min ago'
tail -100 /var/log/postgresql/postgresql-*.log

常见根因

  1. 服务未启动、端口错误或 listen_addresses 只监听本地。
  2. pg_hba.conf 没有匹配的客户端地址或认证方式。
  3. 密码错误、角色不存在,或数据库不存在。
  4. 连接数达到 max_connections,连接池泄漏。
  5. SSL 模式不匹配:sslmode=require 但服务端未启用 TLS。
  6. 防火墙/安全组拦截,或 DNS 解析问题。

修复

相关命令