database connection_error ai_generated true

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

Also available as: JSON · Markdown · 中文
90%Fix Rate
90%Confidence
1Evidence
2023-01-10First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
PostgreSQL 15.4 active
PostgreSQL 16.1 active
PostgreSQL 14.9 active

Root Cause

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.

generic

中文

PostgreSQL Unix 域套接字文件在预期路径上不存在,通常是因为服务器未运行、套接字目录配置错误或客户端在错误的位置查找。

Official Documentation

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

Workarounds

  1. 85% success Start the PostgreSQL server: `sudo systemctl start postgresql` or `pg_ctl start -D /var/lib/postgresql/15/main` (adjust version and data directory).
    Start the PostgreSQL server: `sudo systemctl start postgresql` or `pg_ctl start -D /var/lib/postgresql/15/main` (adjust version and data directory).
  2. 90% success 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.
    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.

中文步骤

  1. Start the PostgreSQL server: `sudo systemctl start postgresql` or `pg_ctl start -D /var/lib/postgresql/15/main` (adjust version and data directory).
  2. 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.

Dead Ends

Common approaches that don't work:

  1. 70% fail

    If the server is not running, TCP/IP connection also fails with 'Connection refused'. This only masks the real issue.

  2. 95% fail

    The issue is server-side (socket file missing), not client-side. Reinstalling clients doesn't fix the server.