psycopg2.OperationalError: 无法连接到服务器:没有那个文件或目录 服务器是否在本地运行并通过 Unix 域套接字 "/var/run/postgresql/.s.PGSQL.5432" 接受连接?
psycopg2.OperationalError: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
ID: database/postgresql-cannot-connect-to-server-no-such-file-or-directory
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| PostgreSQL 15.4 | active | — | — | — |
| PostgreSQL 16.1 | active | — | — | — |
| PostgreSQL 14.9 | active | — | — | — |
根因分析
PostgreSQL Unix 域套接字文件在预期路径上不存在,通常是因为服务器未运行、套接字目录配置错误或客户端在错误的位置查找。
English
The PostgreSQL Unix domain socket file does not exist at the expected path, typically because the server is not running, the socket directory is misconfigured, or the client is looking in the wrong location.
官方文档
https://www.postgresql.org/docs/current/runtime-connection.html解决方案
-
Start the PostgreSQL server: `sudo systemctl start postgresql` or `pg_ctl start -D /var/lib/postgresql/15/main` (adjust version and data directory).
-
If the server is running but socket is in a different directory, set the host parameter to use TCP/IP: `host=localhost port=5432` in the connection string, or set `PGHOST=localhost` environment variable.
无效尝试
常见但无效的做法:
-
70% 失败
If the server is not running, TCP/IP connection also fails with 'Connection refused'. This only masks the real issue.
-
95% 失败
The issue is server-side (socket file missing), not client-side. Reinstalling clients doesn't fix the server.