DEBUG.WIKI
阿里云;从建站到云上业务;云服务器 · 数据库 · 对象存储;查看产品 →
PanstarCloud:部署应用,接入 AI,云服务器与 AI 网关
IPPeak:从目标地区访问网页,住宅代理、SEO 监测、广告验证

解决 PostgreSQL 报错 password authentication failed 认证失败

分析 PostgreSQL 提示 password authentication failed for user 的 pg_hba.conf 鉴权方式冲突与密码重置修复指南。

问题现象

应用程序或命令行连接 PostgreSQL 时抛出认证失败异常:

psql: error: FATAL:  password authentication failed for user "postgres"
FATAL:  password authentication failed for user "app_user"

触发根因

  1. 密码错误或由于包含特殊字符在配置文件中未正确转义。
  2. pg_hba.conf 中的认证机制配置不一致(例如密码是 md5 散列存储的,而 pg_hba.conf 要求 scram-sha-256 校验)。
  3. 本机 peer 认证与密码认证冲突。

解决步骤与操作命令

步骤一:通过操作系统本地 peer 特权免密登录

在 Linux 宿主机上切换为 postgres 系统用户免密登录:

sudo -u postgres psql

步骤二:在线重置目标用户密码

ALTER USER postgres WITH PASSWORD 'NewPostgresPass123!';
ALTER USER app_user WITH PASSWORD 'NewAppUserPass123!';

步骤三:检查并配置 pg_hba.conf 认证规则

编辑 /etc/postgresql/16/main/pg_hba.conf:

# 本地回环与内网网段统一采用 scram-sha-256 密码鉴权
# TYPE  DATABASE        USER            ADDRESS                 METHOD
host    all             all             127.0.0.1/32            scram-sha-256
host    all             all             192.168.1.0/24          scram-sha-256

步骤四:重载 PostgreSQL 配置

sudo systemctl reload postgresql

验证确认

再次运行 psql 测试连接:

PGPASSWORD='NewPostgresPass123!' psql -h 127.0.0.1 -U postgres -d postgres -c "SELECT 1;"

输出 ?column? 1,密码校验成功通过。