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:

  1. Misconfigured pg_hba.conf for local connections:

    • Incorrect TYPE: The rule intended for the connection might be missing a local entry, or an inappropriate host entry is being relied upon for socket connections. local type rules specifically govern connections made via UNIX domain sockets.
    • Incorrect DATABASE or USER: 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 for database="mydb", user="myuser" will reject connections from database="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.
      • peer requires the connecting operating system user to have the same name as the PostgreSQL database user.
      • md5 requires a password to be supplied and for the database user to have a password set.
      • trust allows anyone to connect without a password and is generally insecure for production.
      • ident requires an ident server to be running (less common now).
    • Rule Order: pg_hba.conf rules are processed in order. A broader, less restrictive rule placed before a more specific, restrictive rule can inadvertently cause rejections or unintended access.
  2. PostgreSQL Service Not Running: While the pg_hba.conf part of the error suggests the server is running (otherwise, it couldn’t evaluate pg_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.

  3. Incorrect UNIX Socket Path: PostgreSQL listens on a specific UNIX domain socket path (default: /var/run/postgresql/.s.PGSQL.5432 on 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 indirect pg_hba.conf failure 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.service unit on Debian/Ubuntu is often a wrapper that manages multiple PostgreSQL cluster versions. The active (exited) status is normal for this wrapper, as it delegates to individual cluster services like [email protected]. To check a specific version’s status, use sudo 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 postgres to any database: This is typically the default and allows sudo -u postgres psql to work.

    # TYPE  DATABASE        USER            ADDRESS                 METHOD
    local   all             postgres                                peer

    The peer method authenticates by checking if the operating system user matches the requested database user. If your OS user is postgres and you’re connecting as DB user postgres, 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                                 peer

    This rule allows the OS user webuser to connect to myapp_db as DB user webuser without a password.

  • Connecting as any OS user to any database using md5 password authentication: This is a flexible option, requiring the client to provide a password.

    # TYPE  DATABASE        USER            ADDRESS                 METHOD
    local   all             all                                     md5

    With 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 using md5:

    # 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 webuser access to myapp_db should come before a local all all peer rule if you want different authentication for webuser.
  • ADDRESS column for local connections: The ADDRESS column is ignored for local (UNIX domain socket) connections; leave it blank.
  • TYPE values:
    • local: Matches connections using UNIX domain sockets.
    • host: Matches connections using TCP/IP. (Not relevant for this error, but good to know).
  • METHOD values:
    • 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 trust for 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.

  1. Check the socket directory permissions: The unix_socket_directories setting in postgresql.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-x or similar, owned by postgres:postgres or root:postgres.

  2. Check the socket file itself:

    ls -l /var/run/postgresql/.s.PGSQL.5432 # Adjust path

    Expected 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.5432

    The s at 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 the postgresql.conf file itself (from SHOW config_file;) had an incorrect unix_socket_directories setting, you would need to edit that file and restart PostgreSQL.

[!NOTE] On Debian/Ubuntu, the /var/run/postgresql directory and socket are usually managed correctly by systemd and the postgresql service. 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.