inchTodd/db-error-troubleshooting-skills / skills/pg-could-not-connect-to-server
pg-could-not-connect-to-server
Verified排查 PostgreSQL 报错「connection to server at "%s" (%s), port %s failed: … Is the server running on that host and accepting TCP/IP connections?」。当用户贴出包含这条报错的输出、或问这条报错怎么解决时使用。只读排查优先,不需要也不收集数据库密码。
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 8.8 KB |
SKILL.md
View on GitHub---
name: pg-could-not-connect-to-server
description: "排查 PostgreSQL 报错「connection to server at \"%s\" (%s), port %s failed: … Is the server running on that host and accepting TCP/IP connections?」。当用户贴出包含这条报错的输出、或问这条报错怎么解决时使用。只读排查优先,不需要也不收集数据库密码。"
---
# PostgreSQL「could not connect to server」:连接还没到数据库,先看后缀是 refused、找不到套接字还是超时
> 原文与完整版:https://surinch.com/tools/postgresql-error/could-not-connect-to-server(最后核对 2026-11-05)
## 一句话结论
这条报错由客户端库 libpq 生成,说明连接**还没到达** PostgreSQL,所以和用户名、密码、pg_hba.conf 都无关。看冒号后面的系统错误:`Connection refused` 表示那个地址和端口上没有进程在监听(服务没起、只监听 localhost、端口不对);`No such file or directory` 表示本机套接字文件不存在(服务没起或套接字目录不一致);`timed out` 多半是防火墙或安全组拦截。第一步跑 `pg_isready -h <主机> -p <端口>`。
## 官方报错原文
```
connection to server at "%s" (%s), port %s failed: … Is the server running on that host and accepting TCP/IP connections?
```
出自 libpq 源码 fe-connect.c(REL_18_STABLE)。走 Unix 套接字时是 `connection to server on socket "%s" failed: … Is the server running locally and accepting connections on that socket?`。libpq 13 及以前写作 `could not connect to server: Connection refused / Is the server running on host "%s" (%s) and accepting TCP/IP connections on port %s?`。这是客户端报错,不来自服务器,所以服务器日志里通常没有对应记录。
## 关键事实
| 项 | 内容 |
|---|---|
| 谁报的 | 客户端库 libpq(psql、psycopg、node-postgres 的 pg-native 等),不是服务器 |
| 措辞变化 | libpq 14 起改为 `connection to server ... failed:`,13 及以前是 `could not connect to server:` |
| listen_addresses 默认 | `localhost`:只接受本机 TCP 连接,改动需要重启 |
| 默认端口 / 套接字目录 | `5432`;源码编译默认 `/tmp`,Debian/Ubuntu 软件包常用 `/var/run/postgresql` |
| 快速探测 | `pg_isready` 返回 0 接受连接、1 拒绝(如启动中)、2 无响应、3 参数错误 |
## 按冒号后的系统错误分流
| 你看到的 | 含义 | 先查什么 |
|---|---|---|
| `Connection refused`(TCP) | 目标主机可达,但该端口没有进程监听 | 服务是否在跑;`listen_addresses` 是否包含这块网卡;端口是不是 5432 |
| `No such file or directory`(套接字) | 本机找不到 `.s.PGSQL.<端口>` 套接字文件 | 服务是否在跑;客户端找的目录和服务器 `unix_socket_directories` 是否一致 |
| `Connection timed out` / `Operation timed out` | 包被丢弃,没有任何回应 | 防火墙、云安全组、网络 ACL;地址是不是写错到不可达网段 |
| `could not translate host name` | DNS 解析失败 | 主机名拼写;容器里用服务名而不是 localhost |
| `server closed the connection unexpectedly` | 连上了又被断开 | 不是本页问题:看服务器日志(崩溃、连接数满、SSL 配置) |
```bash
pg_isready -h 127.0.0.1 -p 5432 # 0 = 接受连接,2 = 无响应
ss -ltnp | grep -E ':5432|postgres' # 谁在监听、监听在哪个地址
ls -la /var/run/postgresql/ /tmp/ 2>/dev/null | grep PGSQL # 套接字文件在哪
```
## 本机能连、远程 Connection refused:listen_addresses 还是 localhost
`listen_addresses` 的默认值是 `localhost`,服务器只在回环地址上监听,别的机器连过来就是 Connection refused。这个参数改了要**重启**,reload 不生效。
```sql
SHOW listen_addresses;
SHOW port;
SHOW unix_socket_directories;
-- 改动示例(需要超级用户,写入 postgresql.auto.conf,重启后生效):
-- ALTER SYSTEM SET listen_addresses = '10.0.0.5'; -- 只开放内网网卡,尽量不要直接 '*'
```
> 监听改对后报错如果变成 `no pg_hba.conf entry for host`,说明网络这一层已经通了,接下来改认证规则,见 [no pg_hba.conf entry](https://surinch.com/tools/postgresql-error/no-pg-hba-conf-entry)。
- Debian/Ubuntu 装过两个大版本时,第二个集群通常用 5433。`pg_lsclusters` 列出每个集群的版本、端口和状态。
- Docker:容器内的 PostgreSQL 监听容器里的 5432,宿主机要用 `-p 5432:5432` 映射;另一个容器里连它要写服务名(如 `db`),写 `localhost` 指的是那个容器自己。
## No such file or directory:服务没起,或者客户端去错了目录
不写 `-h` 时客户端走 Unix 套接字,去编译时定好的目录里找 `.s.PGSQL.5432`。源码编译默认是 `/tmp`,Debian/Ubuntu 的软件包通常是 `/var/run/postgresql`。用 A 来源的客户端连 B 来源的服务器,就可能去错目录。
```bash
# 服务器到底在不在跑
systemctl status postgresql # 或 pg_lsclusters(Debian/Ubuntu)
ps -ef | grep -v grep | grep postgres
# 服务器在跑、只是目录不同:显式指定套接字目录
psql -h /var/run/postgresql -U postgres
```
如果服务确实没起,去看服务器日志里最后几行启动错误(端口被占、数据目录权限、配置语法错误),而不是反复重试连接。
## postmaster.pid:网上常说删掉就好,删之前先确认没有进程在跑
机器断电或进程被强杀后,数据目录里可能留下旧的 `postmaster.pid`,服务器启动时会报 `lock file "postmaster.pid" already exists` 而起不来,客户端就一直是 could not connect。网上流传的“删掉 postmaster.pid”只适用于**确认没有任何 postgres 进程在跑**的情况。
1. 先 `ps -ef | grep postgres`,并看 pid 文件第一行记录的进程号是否还存在。
2. 还有进程在跑时删除 pid 文件再启动第二个实例,可能导致两个进程同时写同一个数据目录,造成数据损坏。
3. 拿不准时先完整备份数据目录(停机状态下拷贝),再操作;生产库建议找 DBA 处理。
## 常见问题
**psql: could not connect to server: Connection refused 怎么解决?**
说明目标端口上没有进程在监听。先用 pg_isready 和 ss -ltnp 确认服务是否在跑、监听在哪个地址和端口;远程连接还要把 listen_addresses 从默认的 localhost 改成对应网卡地址并重启。
**No such file or directory, Is the server running locally 是什么意思?**
客户端在本机套接字目录里找不到 .s.PGSQL.5432。要么服务没启动,要么客户端和服务器用的套接字目录不同(/tmp 和 /var/run/postgresql),可以用 psql -h /var/run/postgresql 指定目录。
**这个报错和用户名密码有关系吗?**
没有。连接还没到服务器,认证根本没开始。用户名或密码错误会是 password authentication failed 等其他报错。
**改了 listen_addresses 为什么还是连不上?**
listen_addresses 需要重启服务器才生效,reload 不够。重启后还要在 pg_hba.conf 里为客户端地址加 host 规则,并检查防火墙和云安全组。
**可以直接删除 postmaster.pid 吗?**
只有确认没有任何 postgres 进程在运行时才可以。有进程在跑时删除并再启动一个实例,可能让两个进程同时写数据目录,造成损坏。
## 给 agent 的使用守则
- 先让用户贴出完整报错和执行的命令,按上面的顺序做只读检查,再给修改建议。
- 不要求用户提供密码、连接串里的凭证或生产数据;需要时让用户自己在本机执行命令并贴结果(可先打码)。
- 改配置(pg_hba.conf、my.cnf、授权语句)前先说明影响并让用户确认;本 skill 不承诺任何修复效果。
## 来源
- [PostgreSQL 源码 REL_18_STABLE:src/interfaces/libpq/fe-connect.c(connectFailureMessage)](https://github.com/postgres/postgres/blob/REL_18_STABLE/src/interfaces/libpq/fe-connect.c)
- [PostgreSQL 源码 REL_13_STABLE:src/interfaces/libpq/fe-connect.c(libpq 13 及以前的旧版措辞)](https://github.com/postgres/postgres/blob/REL_13_STABLE/src/interfaces/libpq/fe-connect.c)
- [PostgreSQL 18 文档 19.3:Connections and Authentication(listen_addresses、port、unix_socket_directories)](https://www.postgresql.org/docs/current/runtime-config-connection.html)
- [PostgreSQL 18 文档:pg_isready](https://www.postgresql.org/docs/current/app-pg-isready.html)
- [PostgreSQL 18 文档 18.3:Starting the Database Server(含 postmaster.pid 与常见启动失败)](https://www.postgresql.org/docs/current/server-start.html)
- [Debian postgresql-common:pg_lsclusters(1) 手册](https://manpages.debian.org/bookworm/postgresql-common/pg_lsclusters.1.en.html)
完整图文版和相关报错:https://surinch.com/tools/postgresql-error/could-not-connect-to-server
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| 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: 119k | Updated | Claude CodeCodex | Verified | Install |
| 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: 119k | Updated | Claude CodeCodex | Verified | Install |
| 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: 118k | Updated | Claude CodeCodex | Verified | Install |
| 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: 118k | Updated | Claude CodeCodex | Verified | Install |