系统学习 故障排查学习路径:从方法论到系统、网络、数据库与 K8s

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 解析问题。

修复

相关命令

参考链接

读完自测

合上页面,先回答,再展开对照。

  1. 先用什么命令确认 PostgreSQL 服务可用和端口监听?
  2. 报 no pg_hba.conf entry 说明什么,应如何修复?
  3. 客户端报 SSL error 时常见原因是什么?
答案
  1. 用 pg_isready -h <host> -p 5432 确认服务,用 ss -lntp | grep 5432 确认监听。
  2. pg_hba.conf 没有匹配客户端地址或认证方式的条目;修改 pg_hba.conf(必要时同时调整 listen_addresses)后 reload 再重试。
  3. 常见于 sslmode=require 但服务端未启用 TLS;检查 SHOW ssl、服务端 SSL 配置和客户端 sslmode,并统一证书。
微信小程序码:扫码打开命令速查小程序

小程序版

微信扫码,随时查命令