Tag: pg_hba.conf

  • PostgreSQL pg_hba.conf Connection Authorization Failed on CentOS Stream / Rocky Linux

    Troubleshoot and resolve 'connection authorization failed' errors in PostgreSQL on CentOS Stream and Rocky Linux by correctly configuring pg_hba.conf and related settings.

    When working with PostgreSQL on CentOS Stream or Rocky Linux, encountering a "connection authorization failed" error indicates that the database server successfully received your connection request but explicitly denied it based on its access control rules. This guide provides a comprehensive, expert-level approach to diagnose and resolve this common issue, ensuring your applications and users can connect securely.

    Symptom & Error Signature

    The primary symptom is an inability to connect to your PostgreSQL database, typically from a client application, a command-line psql utility, or another server. You will usually see a FATAL error message.

    Typical psql command line error:

    $ psql -h your_db_host -U your_db_user -d your_db_name
    psql: FATAL:  connection authorization failed for user "your_db_user"
    psql: FATAL:  no pg_hba.conf entry for host "your_client_ip", user "your_db_user", database "your_db_name", no encryption

    Common application error (e.g., Python with psycopg2):

    # Example output from a Python application attempting to connect
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    psycopg2.OperationalError: FATAL:  connection authorization failed for user "web_app_user"
    FATAL:  no pg_hba.conf entry for host "192.168.1.100", user "web_app_user", database "webapp_db"

    PostgreSQL server log entries (found in /var/lib/pgsql/data/log/postgresql-*.log or journalctl -u postgresql-1X):

    202X-XX-XX XX:XX:XX UTC [12345] LOG:  connection received: host=192.168.1.100 port=54321
    202X-XX-XX XX:XX:XX UTC [12345] FATAL:  no pg_hba.conf entry for host "192.168.1.100", user "web_app_user", database "webapp_db", no encryption
    ```

    Root Cause Analysis

    The "connection authorization failed" error almost exclusively points to an incorrect or missing entry in PostgreSQL's Host-Based Authentication (HBA) configuration file, pg_hba.conf. This file controls which hosts are allowed to connect, which users they can connect as, which databases they can access, and what authentication method is required.

    The underlying reasons typically fall into one of these categories:

    1. Missing pghba.conf Entry: The most common cause. There is no rule in pghba.conf that matches the incoming connection's parameters (source IP, user, database).
    2. Incorrect pg_hba.conf Entry: An existing entry is present, but one or more of its fields (e.g., source IP, user, database, authentication method) do not precisely match the connection attempt.
    3. Incorrect Order of Rules: pg_hba.conf rules are processed sequentially from top to bottom. The first rule that matches the connection attempt is used. If a broad, less secure rule appears before a more specific, secure rule, it might inadvertently allow or deny connections in unexpected ways.
    4. Incorrect Authentication Method: The pg_hba.conf entry specifies an authentication method (e.g., scram-sha-256, md5, trust, peer, ident) that doesn't match the client's provided credentials or the server's configured user password.
    5. * scram-sha-256: The modern, recommended secure password-based authentication.
    6. * md5: An older, less secure password-based authentication, still widely used.
    7. * trust: Allows anyone to connect without a password (highly insecure for non-local connections).
    8. * peer: Used for local connections where the operating system user matches the database user.
    9. * ident: Similar to peer, relies on an ident server on the client for authentication.
    10. listenaddresses Misconfiguration: While this usually results in "connection refused," if listenaddresses in postgresql.conf is set to localhost or 127.0.0.1 and a remote client tries to connect, the connection will not even reach the pg_hba.conf stage for remote IP addresses. It's essential to ensure PostgreSQL is listening on the correct network interfaces (e.g., * for all, or specific IP addresses).
    11. Incorrect Database/User Permissions: Even if pghba.conf allows the connection, the user might not have CONNECT privileges on the requested database or USAGE on specific schemas, leading to application errors after authentication. This is different from the pghba.conf error but often confused.

    Step-by-Step Resolution

    Follow these steps carefully to diagnose and resolve the pg_hba.conf connection authorization error.

    1. Locate pg_hba.conf and postgresql.conf

    First, you need to find the correct configuration files. The location can vary slightly depending on the PostgreSQL version and installation method.

    # Log in as the postgres user (or use sudo) to execute psql commands
    sudo -u postgres psql -c 'SHOW hba_file;'
    sudo -u postgres psql -c 'SHOW config_file;'

    Common locations on CentOS Stream / Rocky Linux for PostgreSQL 12-16:

    • pghba.conf: /var/lib/pgsql/data/pghba.conf (for older versions/manual setup) or /var/lib/pgsql/1X/data/pg_hba.conf (where 1X is your PostgreSQL major version, e.g., 15).
    • postgresql.conf: /var/lib/pgsql/data/postgresql.conf or /var/lib/pgsql/1X/data/postgresql.conf.

    [!NOTE] On modern CentOS/Rocky systems, PostgreSQL is often installed via dnf, and the data directory is version-specific (e.g., /var/lib/pgsql/15/data).

    2. Backup Original Configuration Files

    Before making any changes, always back up your configuration files.

    PG_VERSION=$(sudo -u postgres psql -t -P format=unaligned -c 'SHOW hba_file;' | cut -d'/' -f5) # Extracts '15' from '/var/lib/pgsql/15/data/pg_hba.conf'

    sudo cp ${PGCONFIGDIR}/pghba.conf ${PGCONFIGDIR}/pghba.conf.bak.$(date +%F-%H%M) sudo cp ${PGCONFIGDIR}/postgresql.conf ${PGCONFIGDIR}/postgresql.conf.bak.$(date +%F-%H%M) `

    3. Understand pg_hba.conf Syntax

    Each line in pg_hba.conf defines an access rule. Comments start with #. Blank lines are ignored. A rule typically follows this format:

    TYPE DATABASE USER ADDRESS METHOD [OPTIONS]

    • TYPE: Specifies the connection type.
    • * local: Connections via Unix-domain sockets (local access only).
    • * host: Connections via TCP/IP (both IPv4 and IPv6).
    • * hostssl: TCP/IP connections only if SSL is used.
    • hostnossl: TCP/IP connections only if SSL is not* used.
    • DATABASE: Which database(s) this rule applies to. Can be all, a specific database name, or replication (for streaming replication).
    • USER: Which user(s) this rule applies to. Can be all, a specific user name, or a group name prefixed with +.
    • ADDRESS: The client's IP address range or host.
    • * 127.0.0.1/32 or localhost: Only from the local machine (IPv4).
    • * ::1/128: Only from the local machine (IPv6).
    • * 0.0.0.0/0: All IPv4 addresses (highly insecure for most authentication methods).
    • * 192.168.1.0/24: A specific network range.
    • * 10.0.0.10/32: A single specific IP address.
    • METHOD: The authentication method. scram-sha-256 (recommended), md5, trust, peer, ident, gssapi, ssi.
    • OPTIONS: Additional options specific to the authentication method.

    4. Edit pg_hba.conf to Allow Connections

    Using the information from the error message (client IP, user, database), add or modify an entry in pg_hba.conf. Open the file with your preferred text editor (e.g., vi or nano).

    sudo vi ${PG_CONFIG_DIR}/pg_hba.conf

    Common Scenarios and Solutions:

    Scenario 1: Allow a specific application user from a specific IP address (most common and recommended). Add this line at the end of your pg_hba.conf file, or logically group it with other host entries:

    # TYPE  DATABASE        USER            ADDRESS                 METHOD
    host    webapp_db       web_app_user    192.168.1.100/32        scram-sha-256
    ```
    *   Replace `webapp_db` with your database name.
    *   Replace `web_app_user` with your database username.
    *   Replace `192.168.1.100/32` with the *exact IP address* of the client connecting to PostgreSQL. Use `/32` for a single IPv4 address or `/128` for a single IPv6 address. For a network, use the appropriate CIDR (e.g., `192.168.1.0/24`).

    Scenario 2: Allow all users from localhost for a specific database (for local applications/CLI tools).

    # TYPE  DATABASE        USER            ADDRESS                 METHOD
    host    your_db_name    all             127.0.0.1/32            scram-sha-256
    host    your_db_name    all             ::1/128                 scram-sha-256

    Scenario 3: Allow local connections using peer authentication (recommended for local postgres user). This is typically already present and allows the Linux postgres user to connect to PostgreSQL as the postgres database user via Unix sockets without a password.

    # TYPE  DATABASE        USER            ADDRESS                 METHOD
    local   all             postgres                                peer

    [!WARNING] Avoid using trust for remote connections (host) as it allows anyone to connect without any authentication. Only use trust for local connections in highly controlled environments or for specific, temporary debugging.

    host all all 0.0.0.0/0 md5 – This rule is highly insecure as it allows all users from any IP to connect to any database using a password. Only use 0.0.0.0/0 if you have very strict firewall rules in place, and even then, consider restricting it.

    5. Verify listen_addresses in postgresql.conf

    While pg_hba.conf handles authorization, postgresql.conf determines where PostgreSQL listens for connections. If PostgreSQL isn't listening on the correct network interface, remote connections will result in "connection refused," not "authorization failed." However, it's a common point of confusion.

    Open postgresql.conf:

    sudo vi ${PG_CONFIG_DIR}/postgresql.conf

    Find the listen_addresses parameter and ensure it's configured correctly:

    # What IP address(es) to listen on; '*' means all IP interfaces.
    # In a production environment, it is best to be explicit.
    #listen_addresses = 'localhost'         # (change requires restart)
    listen_addresses = '*'                  # Listen on all available interfaces
    #listen_addresses = '192.168.1.50,localhost' # Listen on specific IPs and localhost

    [!IMPORTANT] Changing listen_addresses requires a restart of the PostgreSQL service, not just a reload.

    6. Reload or Restart PostgreSQL

    After modifying pghba.conf, you must reload PostgreSQL for the changes to take effect. If you changed listenaddresses in postgresql.conf, a full restart is required.

    Reload (for pg_hba.conf changes):

    # Get the PostgreSQL service name (e.g., postgresql-15)

    sudo systemctl reload ${PG_SERVICE} `

    Restart (for postgresql.conf changes or if reload doesn't work):

    sudo systemctl restart ${PG_SERVICE}

    [!NOTE] systemctl reload is generally preferred as it doesn't drop existing connections. However, if issues persist or if listen_addresses was changed, a restart is necessary.

    7. Check Firewall Rules (firewalld)

    While less likely to cause an "authorization failed" error (which implies the connection reached PostgreSQL), firewall rules can prevent connections entirely, leading to "connection refused." It's a good practice to verify if you're troubleshooting any connection issue.

    PostgreSQL typically listens on port 5432. Ensure this port is open on your CentOS Stream/Rocky Linux server.

    # Check current firewall status

    If port 5432 is not listed, add it (for public zone, adjust if needed) sudo firewall-cmd –zone=public –add-port=5432/tcp –permanent sudo firewall-cmd –reload `

    8. Verify PostgreSQL User and Password

    Ensure the database user exists and has the correct password set, matching the authentication method in pg_hba.conf.

    # Connect as the postgres superuser

    List users and their attributes (look for your user) du

    If the user doesn't exist, create it: CREATE USER webappuser WITH PASSWORD 'averystrong_password' VALID UNTIL '2028-01-01';

    If the password needs to be set/reset (especially for scram-sha-256): ALTER USER webappuser WITH PASSWORD 'newstrongpassword';

    Grant connect privileges to the database (if not already done) GRANT CONNECT ON DATABASE webappdb TO webapp_user;

    Quit psql q `

    [!IMPORTANT] PostgreSQL 10+ defaults to scram-sha-256 for new password hashes. If your pghba.conf uses md5 and the user password was created more recently, there might be a mismatch. You can explicitly set the password using ALTER USER ... WITH PASSWORD ... and ensure pghba.conf matches.

    9. Test the Connection

    After making all changes and reloading/restarting PostgreSQL, attempt to connect again from your client or application.

    # From the client machine or server itself
    psql -h your_db_host -U your_db_user -d your_db_name

    If successful, you should be prompted for a password (if using scram-sha-256 or md5) and then connect to the database. If the error persists, carefully review the PostgreSQL logs for the exact FATAL message and re-check each step, paying close attention to IP addresses, user names, database names, and authentication methods in your pg_hba.conf file.

  • 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 pghba.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 pghba.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 pghba.conf failed" error primarily stems from misconfigurations within the pghba.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:
    2. * 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.
    3. * 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".
    4. * 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.
    5. * peer requires the connecting operating system user to have the same name as the PostgreSQL database user.
    6. * md5 requires a password to be supplied and for the database user to have a password set.
    7. * trust allows anyone to connect without a password and is generally insecure for production.
    8. * ident requires an ident server to be running (less common now).
    9. * 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.
    1. PostgreSQL Service Not Running: While the pghba.conf part of the error suggests the server is running (otherwise, it couldn't evaluate pghba.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.
    1. 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

    … (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 pghba.conf and unixsocket_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

    config_file ——————————- /etc/postgresql/14/main/postgresql.conf (1 row)

    unixsocketdirectories ————————- /var/run/postgresql (1 row) ` Make a note of these paths. The hbafile output tells you exactly which pghba.conf to edit. The unixsocketdirectories 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.
    • `conf
    • # 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.
    • `conf
    • # 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.
    • `conf
    • # 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 'yoursecurepassword';).
    • Connecting as a specific DB user (e.g., dashboard_user) from any local OS user using md5:
    • `conf
    • # TYPE DATABASE USER ADDRESS METHOD
    • local dashboarddb dashboarduser 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):

    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:
    2. The unixsocketdirectories setting in postgresql.conf (which you found in Step 2) indicates where the socket should be. Ensure this directory exists and has appropriate permissions.
    3. `bash
    4. ls -ld /var/run/postgresql/ # Adjust path as per 'SHOW unixsocketdirectories;'
    5. `
    6. Expected permissions: drwxrwxr-x or similar, owned by postgres:postgres or root:postgres.
    1. Check the socket file itself:
    2. `bash
    3. ls -l /var/run/postgresql/.s.PGSQL.5432 # Adjust path
    4. `
    5. Expected output should show the socket file existing and owned by postgres:postgres.
    6. `
    7. srwxrwxrwx 1 postgres postgres 0 Jun 27 10:45 /var/run/postgresql/.s.PGSQL.5432
    8. `
    9. 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 configfile;) had an incorrect unixsocket_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.