# psycopg2.OperationalError: 无法连接到服务器：没有那个文件或目录
	服务器是否在本地运行并接受 Unix 套接字 "/var/run/postgresql/.s.PGSQL.5432" 上的连接？

- **ID:** `database/postgresql-cannot-connect-to-server-no-such-file`
- **领域:** database
- **类别:** connection_error
- **验证级别:** ai_generated
- **修复率:** 85%

## 根因

PostgreSQL 未运行或 Unix 套接字文件丢失，通常是因为 postgres 服务已停止、套接字目录配置错误，或者服务器以不同的套接字路径启动。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| PostgreSQL 16.3 | active | — | — |
| PostgreSQL 15.7 | active | — | — |
| PostgreSQL 14.12 | active | — | — |

## 解决方案

1. ```
   Check if PostgreSQL is running: systemctl status postgresql (or pg_isready). If not running, start it: systemctl start postgresql (or pg_ctl start -D /var/lib/postgresql/16/main).
   ```
2. ```
   If the socket path is misconfigured, update postgresql.conf to set unix_socket_directories to the correct path (e.g., /var/run/postgresql), then restart: sudo systemctl restart postgresql.
   ```
3. ```
   As a workaround, connect via TCP instead of Unix socket by specifying host='localhost' in the connection string: psql -h localhost -U myuser mydb.
   ```

## 无效尝试

- **Changing the port in the connection string to a different port (e.g., from 5432 to 5433)** — The error is about the socket file, not the port; changing the port will only work if the server listens on that port via TCP, but the socket path remains the same. (90% 失败率)
- **Creating a symbolic link to the socket file manually (ln -s /tmp/.s.PGSQL.5432 /var/run/postgresql/.s.PGSQL.5432)** — The socket file is created by PostgreSQL at startup; a manual symlink will not be valid if the server is not running, and it may cause permission issues. (85% 失败率)
- **Restarting only the application without checking PostgreSQL** — The application restart does not affect the database server; the connection will still fail if PostgreSQL is down. (100% 失败率)
