database connection_error ai_generated true

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 socket "/var/run/postgresql/.s.PGSQL.5432"?

ID: database/postgresql-cannot-connect-to-server-no-such-file

其他格式: JSON · Markdown 中文 · English
85%修复率
89%置信度
1证据数
2024-01-12首次发现

版本兼容性

版本状态引入弃用备注
PostgreSQL 16.3 active
PostgreSQL 15.7 active
PostgreSQL 14.12 active

根因分析

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

English

PostgreSQL is not running or the Unix socket file is missing, often because the postgres service is stopped, the socket directory is misconfigured, or the server was started with a different socket path.

generic

官方文档

https://www.postgresql.org/docs/16/runtime-config-connection.html

解决方案

  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.

无效尝试

常见但无效的做法:

  1. Changing the port in the connection string to a different port (e.g., from 5432 to 5433) 90% 失败

    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.

  2. Creating a symbolic link to the socket file manually (ln -s /tmp/.s.PGSQL.5432 /var/run/postgresql/.s.PGSQL.5432) 85% 失败

    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.

  3. Restarting only the application without checking PostgreSQL 100% 失败

    The application restart does not affect the database server; the connection will still fail if PostgreSQL is down.