# 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`
- **Domain:** database
- **Category:** connection_error
- **Verification:** ai_generated
- **Fix Rate:** 85%

## Root Cause

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.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| PostgreSQL 16.3 | active | — | — |
| PostgreSQL 15.7 | active | — | — |
| PostgreSQL 14.12 | active | — | — |

## Workarounds

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).** (90% success)
   ```
   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.** (85% success)
   ```
   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.** (80% success)
   ```
   As a workaround, connect via TCP instead of Unix socket by specifying host='localhost' in the connection string: psql -h localhost -U myuser mydb.
   ```

## Dead Ends

- **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% fail)
- **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% fail)
- **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% fail)
