错误提示:
FATAL: no pg_hba.conf entry for host "114.254.95.19", user "postgres", database "postgres", no encryption
如果你在连接 PostgreSQL 时遇到这个报错,那么这篇文章将彻底帮你解决问题。
🧠 问题分析
这是 PostgreSQL 的身份验证失败错误。它来自 pg_hba.conf
(host-based authentication)文件控制规则。
该错误意味着:
- PostgreSQL 收到远程连接请求(如 IP
114.254.95.19
); - 使用了 未加密方式 连接(通常是 TCP/IP);
- 但在
pg_hba.conf
文件中 没有匹配的认证规则; - 因此连接被直接拒绝。
✅ 解决思路一览
我们需要做三件事:
- 🛡️ 修改
pg_hba.conf
—— 明确允许该主机连接; - 📢 修改
postgresql.conf
—— 启用远程监听; - 🔄 重启 PostgreSQL 服务 —— 让配置生效。
🛠️ 步骤详解
1️⃣ 找到 pg_hba.conf
文件
在终端或 psql
中运行:
SHOW hba_file;
或者手动查找路径(示例):
- Windows:
C:\Program Files\PostgreSQL\17\data\pg_hba.conf
- Linux:
/var/lib/pgsql/17/data/pg_hba.conf
2️⃣ 修改 pg_hba.conf
在文件末尾添加一条规则:
# 允许来自任意 IPv4 地址的连接
host all all 0.0.0.0/0 scram-sha-256
🔒 如果你只希望允许特定 IP:
host all all 114.254.95.19/32 scram-sha-256
建议使用 scram-sha-256
(更安全),不推荐使用 trust
或 password
(不加密)。
3️⃣ 修改 postgresql.conf
(允许监听远程地址)
查找:
listen_addresses = 'localhost'
改为:
listen_addresses = '*'
或更精细控制:
listen_addresses = 'localhost,114.254.95.19'
4️⃣ 重启 PostgreSQL 服务(Windows 示例)
📍 查找服务名:
在 PowerShell 中运行:
sc.exe query type= service | findstr /I "postgres"
示例输出:
SERVICE_NAME: postgresql-x64-17
🚀 重启服务:
net stop postgresql-x64-17 && net start postgresql-x64-17
✅ 验证连接是否成功
- 使用 DBeaver / Navicat / psql 等工具远程连接;
- 地址填写 PostgreSQL 服务器的公网或内网 IP;
- 用户名
postgres
,端口通常是5432
; - 成功即表示配置生效。
🔐 安全建议
- 不要在公网暴露
0.0.0.0/0
,使用防火墙限制 IP; - 强制使用
scram-sha-256
密码加密认证; - 给每个远程用户分配专属账户和最小权限。
📝 常见报错对照表
报错信息 | 原因 | 解决方法 |
---|---|---|
no pg_hba.conf entry for host ... no encryption |
没有认证规则 | 在 pg_hba.conf 中添加匹配项 |
FATAL: password authentication failed for user "postgres" |
密码错误 | 检查连接密码是否正确 |
psql: could not connect to server: Connection refused |
服务没启动或端口未开放 | 启动服务并确认监听端口 |
psql: could not connect to server: No route to host |
网络不通或防火墙拦截 | 检查网络连通性、开放端口 |
connection requires a valid client certificate (若启用 SSL) |
强制使用了 SSL | 在连接配置中启用 SSL,或关闭服务器端 SSL 要求 |
✅ 总结
通过本文你将能够:
- 理解
pg_hba.conf
错误的成因; - 精确配置远程访问规则;
- 安全地允许 PostgreSQL 远程连接;
- 避免最常见的配置误区。