Troubleshooting PostgreSQL 'Connection to server on socket pg_hba.conf failed' Error
Resolve the common PostgreSQL 'connection to server on socket pg_hba.conf failed' error. This guide covers server status, UNIX socket paths, and critical pg_hba.conf authentication issues for local connections.
This comprehensive guide delves into resolving the “PostgreSQL connection to server on socket pg_hba.conf failed” error, a common roadblock for developers and system administrators. This specific error indicates that while the PostgreSQL server might be running and its UNIX domain socket is accessible, the server’s authentication rules, defined in pg_hba.conf, are preventing the connection from being established. Understanding and correctly configuring pg_hba.conf for local socket connections is crucial for securing and ensuring the operability of your PostgreSQL instances.
Symptom & Error Signature
Users typically encounter this error when attempting to connect to a local PostgreSQL database via the psql command-line client or when an application (e.g., a web application, background worker) tries to establish a connection. The exact error message can vary slightly but will prominently feature the socket path and a rejection related to pg_hba.conf.
Typical psql output:
psql: error: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: FATAL: pg_hba.conf rejects connection for host "local", user "youruser", database "yourdb"
Application Log Output Example (e.g., a Python application using psycopg2):
2026-06-27 10:30:05,123 ERROR [app.py] Database connection failed:
psycopg2.OperationalError: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: FATAL: pg_hba.conf rejects connection for host "local", user "web_app_user", database "webapp_db"
This error explicitly indicates that the connection attempt reached the PostgreSQL server via the specified UNIX socket, but the server subsequently denied access based on its host-based authentication rules.
Root Cause Analysis
The “PostgreSQL connection to server on socket pg_hba.conf failed” error primarily stems from misconfigurations within the pg_hba.conf file for local UNIX domain socket connections. However, related issues like the server not running or incorrect socket paths can sometimes manifest similarly or be prerequisites for troubleshooting.
Here’s a breakdown of the underlying reasons:
-
Misconfigured
pg_hba.confforlocalconnections:- Incorrect
TYPE: The rule intended for the connection might be missing alocalentry, or an inappropriatehostentry is being relied upon for socket connections.localtype rules specifically govern connections made via UNIX domain sockets. - Incorrect
DATABASEorUSER: The rule might specify a database or user name that does not match the one being used by the connecting client. For example, a rule fordatabase="mydb", user="myuser"will reject connections fromdatabase="otherdb", user="myuser". - Inappropriate
METHOD: The authentication method specified (peer,md5,trust,ident, etc.) does not match how the client is attempting to authenticate or is not correctly configured on the system.peerrequires the connecting operating system user to have the same name as the PostgreSQL database user.md5requires a password to be supplied and for the database user to have a password set.trustallows anyone to connect without a password and is generally insecure for production.identrequires anidentserver to be running (less common now).
- Rule Order:
pg_hba.confrules are processed in order. A broader, less restrictive rule placed before a more specific, restrictive rule can inadvertently cause rejections or unintended access.
- Incorrect
-
PostgreSQL Service Not Running: While the
pg_hba.confpart of the error suggests the server is running (otherwise, it couldn’t evaluatepg_hba.conf), it’s a fundamental prerequisite for any connection. If the server isn’t running, the error would typically be “Connection refused” or “No such file or directory” for the socket. However, it’s always the first diagnostic step. -
Incorrect UNIX Socket Path: PostgreSQL listens on a specific UNIX domain socket path (default:
/var/run/postgresql/.s.PGSQL.5432on Debian/Ubuntu). If the client application is configured to connect to a different path, or if the server itself is configured to use a non-default path, the connection will fail. This usually results in a “No such file or directory” error for the socket file, but an indirectpg_hba.conffailure can occur if a proxy or wrapper is involved.
Step-by-Step Resolution
Follow these steps to diagnose and resolve the “PostgreSQL connection to server on socket pg_hba.conf failed” error.
1. Verify PostgreSQL Service Status
Ensure the PostgreSQL service is actively running on your system. This is a critical first step for any connection issue.
sudo systemctl status postgresql
Expected Output (running):
â—Ź postgresql.service - PostgreSQL RDBMS
Loaded: loaded (/lib/systemd/system/postgresql.service; enabled; vendor preset: enabled)
Active: active (exited) since Fri 2026-06-27 09:00:00 UTC; 1h ago
Process: 1234 ExecStart=/bin/true (code=exited, status=0/SUCCESS)
Main PID: 1234 (code=exited, status=0/SUCCESS)
Tasks: 0 (limit: 4616)
Memory: 0B
CGroup: /system.slice/postgresql.service
... (details about individual cluster processes)
If the status is inactive or failed, start the service and enable it to start on boot:
sudo systemctl start postgresql
sudo systemctl enable postgresql
[!IMPORTANT] The
postgresql.serviceunit on Debian/Ubuntu is often a wrapper that manages multiple PostgreSQL cluster versions. Theactive (exited)status is normal for this wrapper, as it delegates to individual cluster services like[email protected]. To check a specific version’s status, usesudo systemctl status postgresql@<version>-<cluster_name>. E.g.,sudo systemctl status postgresql@14-main.
2. Locate pg_hba.conf and unix_socket_directories
Before making changes, you need to know the exact location of your pg_hba.conf file and which directories PostgreSQL is configured to use for its UNIX domain sockets.
Connect as the postgres superuser (or any user with appropriate permissions) and query the database:
sudo -u postgres psql -c 'SHOW hba_file;'
sudo -u postgres psql -c 'SHOW config_file;'
sudo -u postgres psql -c 'SHOW unix_socket_directories;'
Example Output:
hba_file
----------------------------
/etc/postgresql/14/main/pg_hba.conf
(1 row)
config_file
-------------------------------
/etc/postgresql/14/main/postgresql.conf
(1 row)
unix_socket_directories
-------------------------
/var/run/postgresql
(1 row)
Make a note of these paths. The hba_file output tells you exactly which pg_hba.conf to edit. The unix_socket_directories output confirms where the server expects its socket.
3. Inspect and Edit pg_hba.conf for Local Socket Rules
Open the pg_hba.conf file using your preferred text editor (e.g., nano, vi). Remember to use sudo for elevated permissions.
sudo nano /etc/postgresql/14/main/pg_hba.conf # Adjust path based on your 'SHOW hba_file;' output
Focus on lines that start with local. These lines define authentication rules for UNIX domain socket connections.
Common scenarios and how to configure pg_hba.conf:
-
Connecting as the OS user
postgresto any database: This is typically the default and allowssudo -u postgres psqlto work.# TYPE DATABASE USER ADDRESS METHOD local all postgres peerThe
peermethod authenticates by checking if the operating system user matches the requested database user. If your OS user ispostgresand you’re connecting as DB userpostgres, this works. -
Connecting as an OS user (e.g.,
webuser) to a database (e.g.,myapp_db) as the same DB user (webuser): This is common for application users where the OS user running the app matches the DB user.# TYPE DATABASE USER ADDRESS METHOD local myapp_db webuser peerThis rule allows the OS user
webuserto connect tomyapp_dbas DB userwebuserwithout a password. -
Connecting as any OS user to any database using
md5password authentication: This is a flexible option, requiring the client to provide a password.# TYPE DATABASE USER ADDRESS METHOD local all all md5With this rule, any local connection (via socket) will require a password. Ensure your PostgreSQL users have passwords set (e.g.,
ALTER USER webuser WITH PASSWORD 'your_secure_password';). -
Connecting as a specific DB user (e.g.,
dashboard_user) from any local OS user usingmd5:# TYPE DATABASE USER ADDRESS METHOD local dashboard_db dashboard_user md5
Important considerations when editing pg_hba.conf:
- Order of Rules: Rules are evaluated from top to bottom. The first rule that matches the connection parameters (TYPE, DATABASE, USER, ADDRESS) is used. Place more specific rules before more general rules. For example, a rule allowing
webuseraccess tomyapp_dbshould come before alocal all all peerrule if you want different authentication forwebuser. ADDRESScolumn forlocalconnections: TheADDRESScolumn is ignored forlocal(UNIX domain socket) connections; leave it blank.TYPEvalues:local: Matches connections using UNIX domain sockets.host: Matches connections using TCP/IP. (Not relevant for this error, but good to know).
METHODvalues:peer: Authenticates by obtaining the client’s operating system user name and checking if it matches the requested database user name. No password. Very secure for local system users.md5: Requires the client to supply an MD5-hashed password for authentication.trust: Allows anyone to connect without a password if the connection parameters match.ident: Authenticates by contacting an Ident server on the client to get the client’s OS user name.
[!WARNING] Avoid using
trustfor production environments unless absolutely necessary and with a full understanding of the security implications. It grants unrestricted access to anyone who can connect locally.
Example pg_hba.conf snippet (modified):
# TYPE DATABASE USER ADDRESS METHOD
# Local connections (UNIX domain socket)
# Allow OS user 'postgres' to connect as DB user 'postgres'
local all postgres peer
# Allow OS user 'webuser' to connect to 'myapp_db' as DB user 'webuser'
local myapp_db webuser peer
# Allow any local user to connect to any database using MD5 password authentication
local all all md5
# ... other rules ...
After making your changes, save the pg_hba.conf file.
4. Reload PostgreSQL Configuration
For pg_hba.conf changes to take effect, PostgreSQL needs to reload its configuration. A reload is preferred over a full restart as it doesn’t drop existing connections.
sudo systemctl reload postgresql
If you encounter issues or are unsure, a full restart can also work:
sudo systemctl restart postgresql
5. Verify UNIX Socket Path and Permissions (If pg_hba.conf still doesn’t fix it)
If you’re still facing issues, or if the pg_hba.conf rule seems correct, double-check the actual socket file.
-
Check the socket directory permissions: The
unix_socket_directoriessetting inpostgresql.conf(which you found in Step 2) indicates where the socket should be. Ensure this directory exists and has appropriate permissions.ls -ld /var/run/postgresql/ # Adjust path as per 'SHOW unix_socket_directories;'Expected permissions:
drwxrwxr-xor similar, owned bypostgres:postgresorroot:postgres. -
Check the socket file itself:
ls -l /var/run/postgresql/.s.PGSQL.5432 # Adjust pathExpected output should show the socket file existing and owned by
postgres:postgres.srwxrwxrwx 1 postgres postgres 0 Jun 27 10:45 /var/run/postgresql/.s.PGSQL.5432The
sat the beginning signifies a socket file. If the file is missing after starting PostgreSQL, or has incorrect permissions that prevent the client from accessing it, this can lead to connection failures. In rare cases, if thepostgresql.conffile itself (fromSHOW config_file;) had an incorrectunix_socket_directoriessetting, you would need to edit that file and restart PostgreSQL.
[!NOTE] On Debian/Ubuntu, the
/var/run/postgresqldirectory and socket are usually managed correctly bysystemdand thepostgresqlservice. Manual intervention for permissions here is rarely needed unless you’ve made custom configurations.
6. Test the Connection
After making changes and reloading/restarting PostgreSQL, attempt to connect again using your client or application.
Using psql:
psql -U youruser -d yourdb -h localhost # -h localhost often forces TCP/IP, omit for socket
psql -U youruser -d yourdb # This will default to UNIX socket connection
If you are connecting as an operating system user that has a matching PostgreSQL user and peer authentication is configured:
sudo -u webuser psql -d myapp_db
If the connection is successful, you should see the psql prompt or your application should connect without error.
By systematically working through these steps, you should be able to identify and correct the pg_hba.conf configuration issue preventing your PostgreSQL server from accepting local socket connections.
