Skip to content

inchTodd/db-error-troubleshooting-skills / skills/pg-peer-authentication-failed

pg-peer-authentication-failed

Verified

排查 PostgreSQL 报错「Peer authentication failed for user "%s"」。当用户贴出包含这条报错的输出、或问这条报错怎么解决时使用。只读排查优先,不需要也不收集数据库密码。

FileKindSize
SKILL.mdskill md7.9 KB
---
name: pg-peer-authentication-failed
description: "排查 PostgreSQL 报错「Peer authentication failed for user \"%s\"」。当用户贴出包含这条报错的输出、或问这条报错怎么解决时使用。只读排查优先,不需要也不收集数据库密码。"
---

# PostgreSQL「Peer authentication failed」:操作系统用户名和数据库用户名对不上,换对用户或改走密码认证

> 原文与完整版:https://surinch.com/tools/postgresql-error/peer-authentication-failed(最后核对 2026-11-04)

## 一句话结论

这条报错说明连接命中了 `pg_hba.conf` 里一条 `local ... peer` 规则:peer 方式会从内核取**当前操作系统用户名**,要求它和你要登录的数据库用户名一致。用 Linux 用户 `ubuntu` 执行 `psql -U postgres` 就会失败。最快的改法是 `sudo -u postgres psql`;应用要用密码登录时,改走 TCP(`-h 127.0.0.1`)或把那条 local 规则改成 `scram-sha-256`。

## 官方报错原文

```
Peer authentication failed for user "%s"
```

出自 PostgreSQL 源码 auth.c 的 auth_failed(),错误码 `ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION`(SQLSTATE 28000)。客户端看到的完整形式一般是 `psql: error: connection to server on socket "..." failed: FATAL:  Peer authentication failed for user "postgres"`。

## 关键事实

| 项 | 内容 |
|---|---|
| SQLSTATE | `28000`(invalid_authorization_specification) |
| 只发生在 | `local` 连接(Unix 域套接字);peer 不支持 TCP |
| 比对的是 | 内核报告的客户端操作系统用户名 vs 请求的数据库用户名(可用 `map=` 做映射) |
| 常见来源 | Debian/Ubuntu 的 `pg_createcluster` 默认把本地连接设为 peer |
| 服务器日志额外信息 | `Connection matched ... line N: "..."`,指出命中的是哪一行 |

## 为什么本机连接会走 peer

`psql` 不写 `-h` 时默认走 Unix 域套接字,对应 `pg_hba.conf` 里 `local` 开头的规则。Debian / Ubuntu 用 `pg_createcluster` 建的集群,默认就把本地连接设成 peer。典型规则长这样:

```text
# TYPE  DATABASE  USER      ADDRESS        METHOD
local   all       postgres                 peer
local   all       all                      peer
host    all       all       127.0.0.1/32   scram-sha-256
```

peer 的规则很简单:内核告诉服务器“连过来的是操作系统用户 X”,服务器只允许 X 登录同名的数据库用户。所以下面三种情况都会报这条错:

| 你执行的 | 操作系统用户 | 请求的数据库用户 | 结果 |
|---|---|---|---|
| `psql -U postgres` | `ubuntu` | `postgres` | 失败:名字不一致 |
| `sudo psql -U postgres` | `root` | `postgres` | 失败:sudo 后是 root |
| 应用用 `localhost` 以外的方式连套接字,用户名 `app` | `www-data` | `app` | 失败:服务进程用户不是 app |
| `sudo -u postgres psql` | `postgres` | `postgres` | 成功 |


## 三种改法,按场景选

| 场景 | 做法 | 要不要改配置 |
|---|---|---|
| DBA 在服务器上做管理 | `sudo -u postgres psql`,以 postgres 系统用户执行 | 不用 |
| 应用或脚本要用密码登录 | 连接串写 `-h 127.0.0.1`(或 `localhost`),改走 `host` 规则,用密码认证 | 通常不用;确认 host 行是 scram-sha-256 / md5 |
| 坚持用套接字 + 密码 | 把对应 `local` 行的 `peer` 改成 `scram-sha-256`,并给数据库用户设好密码 | 要,改完 reload |
| 固定的系统用户映射到另一个数据库用户 | `pg_ident.conf` 写映射,`local` 行加 `map=名称` | 要,改完 reload |

```bash
# 1) 管理员:切到 postgres 系统用户
sudo -u postgres psql

# 2) 应用:改走 TCP,使用密码认证
psql -h 127.0.0.1 -U app -d appdb
```

> 改走 TCP 后如果变成 `password authentication failed`,说明 peer 这一步已经过了,接下来查密码,见 [password authentication failed](https://surinch.com/tools/postgresql-error/password-authentication-failed)。


## 用 pg_ident.conf 做用户名映射

官方的 User Name Maps 允许“这个操作系统用户可以以那个数据库用户登录”。例如允许系统用户 `deploy` 以数据库用户 `app` 登录:

```text
# pg_ident.conf
# MAPNAME   SYSTEM-USERNAME   PG-USERNAME
appmap      deploy            app

# pg_hba.conf(这行要放在 local all all peer 之前)
local   appdb   app   peer map=appmap
```

- `pg_hba.conf` 按顺序匹配、**命中第一条就停**,所以带 `map=` 的这行必须放在通用的 `local all all peer` 前面。
- `pg_ident.conf` 同样只在启动和 SIGHUP 时读取,改完执行 `SELECT pg_reload_conf();`。
- PG15 起可以用 `pg_ident_file_mappings` 视图检查映射是否解析成功;PG14 及以前没有这个视图,只能看服务器日志。


## 改 pg_hba.conf 的安全步骤(PG10 及以上)

```sql
SHOW hba_file;
SHOW ident_file;
SELECT line_number, type, database, user_name, address, netmask, auth_method, error
FROM pg_hba_file_rules
ORDER BY line_number;
```

```sql
-- 改完 pg_hba.conf 后,先看有没有语法错误(error 列非空即有问题)
SELECT line_number, error FROM pg_hba_file_rules WHERE error IS NOT NULL;
-- 没有错误再重新加载(不需要重启)
SELECT pg_reload_conf();
```

`pg_hba_file_rules` 显示的是**文件当前内容**,不是服务器已加载的内容,所以可以在 reload 之前先检查。PG16 起服务器日志里的 `Connection matched` 会带上文件名,PG15 及以前只写行号。

## 常见问题

**Peer authentication failed for user "postgres" 怎么解决?**

用 sudo -u postgres psql 以 postgres 系统用户执行。peer 方式要求操作系统用户名和数据库用户名一致,用别的系统用户执行 psql -U postgres 就会失败。

**为什么 sudo psql -U postgres 也不行?**

sudo 之后当前用户是 root,不是 postgres,peer 比对的是 root 和 postgres,所以仍然失败。要写 sudo -u postgres。

**应用连本机 PostgreSQL 报 peer 错误怎么办?**

把连接串的主机写成 127.0.0.1 或 localhost,让连接走 TCP 和 host 规则,用密码认证。peer 只用于 Unix 套接字连接。

**把 peer 改成 trust 可以吗?**

trust 表示不验证身份,任何能连上套接字的系统用户都能以任意数据库用户登录,不建议在有多个系统用户的服务器上使用。需要密码登录就改成 scram-sha-256。

**改了 pg_hba.conf 为什么没生效?**

pg_hba.conf 只在启动和收到 SIGHUP 时读取,改完要执行 SELECT pg_reload_conf() 或 pg_ctl reload。另外规则按顺序匹配,前面已有一条匹配的 peer 行时,后面的改动不会被用到。

## 给 agent 的使用守则

- 先让用户贴出完整报错和执行的命令,按上面的顺序做只读检查,再给修改建议。
- 不要求用户提供密码、连接串里的凭证或生产数据;需要时让用户自己在本机执行命令并贴结果(可先打码)。
- 改配置(pg_hba.conf、my.cnf、授权语句)前先说明影响并让用户确认;本 skill 不承诺任何修复效果。

## 来源

- [PostgreSQL 源码 REL_18_STABLE:src/backend/libpq/auth.c(auth_failed)](https://github.com/postgres/postgres/blob/REL_18_STABLE/src/backend/libpq/auth.c)
- [PostgreSQL 18 文档 20.9:Peer Authentication](https://www.postgresql.org/docs/current/auth-peer.html)
- [PostgreSQL 18 文档 20.2:User Name Maps(pg_ident.conf)](https://www.postgresql.org/docs/current/auth-username-maps.html)
- [PostgreSQL 18 文档 20.1:The pg_hba.conf File](https://www.postgresql.org/docs/current/auth-pg-hba-conf.html)
- [PostgreSQL 18 文档:pg_hba_file_rules 视图](https://www.postgresql.org/docs/current/view-pg-hba-file-rules.html)
- [Debian postgresql-common:pg_createcluster(1) 手册](https://manpages.debian.org/bookworm/postgresql-common/pg_createcluster.1.en.html)

完整图文版和相关报错:https://surinch.com/tools/postgresql-error/peer-authentication-failed
deprecation-and-migrationaddyosmani/agent-skillsManages deprecation and migration. Use when removing old systems, APIs, or features. Use when migrating users from one implementation to another. Use when migrating a database schema in production, such as renaming or dropping a column without downtime (expand/contract). Use when deciding whether to maintain or sunset existing code.Stars: 119kUpdated Claude CodeCodexVerifiedInstall
performance-optimizationaddyosmani/agent-skillsOptimizes application performance across frontend, backend, queries, and databases. Use when performance requirements exist, when you suspect performance regressions, when Core Web Vitals or load times need improvement, when N+1 query patterns need fixing, or when profiling reveals bottlenecks.Stars: 119kUpdated Claude CodeCodexVerifiedInstall
agent-cost-reportthedotmack/claude-memBelievable agent cost report for any period, default the last 7 full days PT, not counting today. Measured tokens from Claude Code transcripts priced at OpenRouter list prices (ESTIMATED), measured provider spend when a sanctioned source exists, note-taker cost separate, Timing-style HTML/PDF plus report.json, line-items.csv, evidence.json.Stars: 118kUpdated Claude CodeCodexVerifiedInstall
agent-cost-reportthedotmack/claude-memBelievable agent cost report for any period, default the last 7 full days PT, not counting today. Measured tokens from Claude Code transcripts priced at OpenRouter list prices (ESTIMATED), measured provider spend when a sanctioned source exists, note-taker cost separate, Timing-style HTML/PDF plus report.json, line-items.csv, evidence.json.Stars: 118kUpdated Claude CodeCodexVerifiedInstall