Skip to content
Solar Account.
Education & Software

How to Reset a PostgreSQL User Password

To reset a PostgreSQL user password, execute ALTER USER username WITH PASSWORD 'new_password'; within an active psql shell session as a database superuser. If you are locked out completely, edit the pg_hba.conf configuration file to set authentication to trust...

How to Reset a PostgreSQL User Password

To reset a PostgreSQL user password, execute ALTER USER username WITH PASSWORD 'new_password'; within an active psql shell session as a database superuser. If you are locked out completely, edit the pg_hba.conf configuration file to set authentication to trust, reload the server, connect without a password to update credentials, and immediately restore original security settings.

Contents

Prerequisites and System Access Requirements

Resetting a password in PostgreSQL depends on your level of privilege within the database cluster and your administrative privileges on the host operating system. Before attempting a password reset, you must identify whether you have active administrative database credentials, access to the database host shell, or administrative access to a managed cloud provider console.

Database Privileges

To change another user's password from within PostgreSQL, your active role must possess either the SUPERUSER attribute or the CREATEROLE attribute. Regular database users can change their own passwords without elevated permissions using the standard ALTER ROLE statement or internal psql meta-commands, provided they can successfully authenticate first.

Operating System Privileges

Reset administrator password - Azure Database for PostgreSQL ...

If you are completely locked out of the postgres superuser account and cannot authenticate through any existing account, you must have administrative root access or sudo privileges on the host operating system (Linux, macOS, or Windows). This host-level access allows you to inspect configuration files, alter authentication rules, switch to the dedicated postgres operating system user, and restart or reload the database service daemon.

Locating Essential Files Across Platforms

PostgreSQL relies on configuration files that govern client authentication and cluster settings. Knowing the locations of these files simplifies recovery operations across different platforms:

  • Debian / Ubuntu Linux: Database configuration files are typically stored in /etc/postgresql//main/pg_hba.conf and /etc/postgresql//main/postgresql.conf.
  • Red Hat / CentOS / Fedora / Rocky Linux: Configurations reside in /var/lib/pgsql/data/pg_hba.conf or /var/lib/pgsql//data/pg_hba.conf.
  • macOS (Homebrew installation): Configuration files are usually located at /usr/local/var/postgres/pg_hba.conf or /opt/homebrew/var/postgresql@/pg_hba.conf.
  • Windows Server / Desktop: Files are found under C:\Program Files\PostgreSQL\\data\pg_hba.conf.

Method 1: Resetting a Password with Active Superuser Access

When you already have an active administrative database connection or access to an account with CREATEROLE privileges, resetting any database account password requires only a simple SQL statement or a dedicated meta-command inside the interactive PostgreSQL terminal (psql).

Using SQL Commands (ALTER ROLE / ALTER USER)

In PostgreSQL syntax, USER and ROLE are largely interchangeable. A user is essentially a role that possesses the LOGIN privilege by default. To alter the password of an existing role, execute the following SQL statement in your database client:

ALTER ROLE target_username WITH PASSWORD 'your_new_secure_password';

Alternatively, you can use the syntax alias:

ALTER USER target_username WITH PASSWORD 'your_new_secure_password';

If you need to set an explicit expiration date on the new credential, append the VALID UNTIL clause:

ALTER ROLE target_username WITH PASSWORD 'your_new_secure_password' VALID UNTIL '2026-12-31 23:59:59+00';

To remove a password requirement entirely (allowing authentication only via passwordless methods such as GSSAPI or client certificates), execute:

ALTER ROLE target_username WITH PASSWORD NULL;

Using the Interactive psql Meta-Command

Executing plain SQL ALTER ROLE commands in interactive shells can expose sensitive credentials to command-history files (such as .bash_history or .psql_history) and central logging utilities if query logging (log_statement = 'all') is enabled on the database server.

To prevent sensitive credentials from remaining in cleartext logs, use the built-in psql command:

  1. Open your terminal and connect to the PostgreSQL instance using psql: psql -U postgres -d postgres
  2. At the database prompt, type the password reset meta-command: \password target_username
  3. Enter your new password when prompted. The client hides your input characters on screen.
  4. Re-enter the password to confirm the change.

Using \password ensures that the database driver encrypts the password client-side before sending it across the wire, suppressing cleartext password output from command histories and server logs.

Method 2: Resetting the Superuser Password When Locked Out

If you lose the password for the primary postgres administrative account and have no other administrative accounts available, you must modify PostgreSQL client authentication controls at the host system level.

Linux Peer Authentication Shortcut

Before modifying configuration files, verify if you have local shell access on a Linux or Unix-based server. By default, many Linux distributions configure local connection rules to use peer authentication. This means the host operating system user postgres can log into the PostgreSQL database user postgres without supplying a password.

To test this access, log into your server terminal and execute:

sudo -i -u postgres

psql

If this command opens the PostgreSQL prompt directly, you do not need to modify configuration files. Simply execute:

ALTER ROLE postgres WITH PASSWORD 'new_secure_password';

Exit the client using \q and return to your normal system account. If peer authentication is disabled or you are running on Windows, proceed with the full recovery procedure below.

Step-by-Step Configuration Recovery Procedure

Step 1: Open the pg_hba.conf File

Log into your host operating system with root or administrative credentials. Open the host authentication configuration file (pg_hba.conf) in a text editor like nano or vim:

sudo nano /etc/postgresql/16/main/pg_hba.conf

Step 2: Temporarily Lower Authentication Requirements

Scroll through the file to find the active local connection rules. These lines specify client IP ranges, database names, usernames, and authentication methods. Look for lines structured like this:

local all all scram-sha-256

host all all 127.0.0.1/32 scram-sha-256

host all all ::1/128 scram-sha-256

Temporarily change the authentication method (the rightmost column) from scram-sha-256, md5, or ident to trust:

local all all trust

host all all 127.0.0.1/32 trust

host all all ::1/128 trust

Setting the rule to trust instructs PostgreSQL to allow any local connection matching these parameters without requiring a password.

Step 3: Reload the PostgreSQL Service

Save your changes and close the editor. Reload or restart the PostgreSQL service daemon so the database engine parses the modified pg_hba.conf file:

On Systemd Linux distributions (Ubuntu, Debian, RHEL): sudo systemctl reload postgresql

On Windows (via Command Prompt as Administrator): net stop postgresql-x64-16 && net start postgresql-x64-16

Step 4: Connect to PostgreSQL Without a Password

Connect to the database instance using the psql client tool. Specify the postgres user and loopback host:

psql -U postgres -h 127.0.0.1

Because of the trust rule, PostgreSQL opens the interactive terminal session immediately without prompting for a password.

Step 5: Reset the Superuser Password

Run the SQL update command to set a new administrative credential:

ALTER ROLE postgres WITH PASSWORD 'new_complex_superuser_password';

Confirm that the server returns ALTER ROLE.

Step 6: Revert Authentication Rules

Exit psql by typing \q. Re-open pg_hba.conf in your text editor:

sudo nano /etc/postgresql/16/main/pg_hba.conf

Revert the modified connection lines back to secure authentication methods (scram-sha-256 is the standard security default):

local all all peer

host all all 127.0.0.1/32 scram-sha-256

host all all ::1/128 scram-sha-256

Step 7: Apply Secure Settings and Verify

Reload the database daemon once more:

sudo systemctl reload postgresql

Verify that password authentication is now enforced by testing a connection with your newly created password:

psql -U postgres -h 127.0.0.1 -W

Method 3: Resetting Passwords on Cloud-Managed Databases

In cloud-managed database services such as AWS RDS, Azure Database for PostgreSQL, or Google Cloud SQL, administrators do not have direct access to the underlying operating system shell or the pg_hba.conf file. Cloud providers manage authentication settings through their own control planes, web consoles, and command-line interfaces (CLIs).

AWS RDS / Aurora for PostgreSQL

In Amazon Web Services, master database credentials can be updated using the AWS Management Console, AWS CLI, or Infrastructure-as-Code utilities.

To reset the password via the AWS CLI, execute:

aws rds modify-db-instance --db-instance-identifier my-db-instance --master-user-password "NewMasterPassword123!" --apply-immediately

The --apply-immediately flag forces AWS to execute the password modification without waiting for the next scheduled maintenance window.

Azure Database for PostgreSQL (Flexible Server)

Microsoft Azure allows administrators to reset the server administrator password directly through the Azure Portal or via the Azure CLI command:

az postgres flexible-server update --resource-group myResourceGroup --name myServerName --admin-password "NewAdminPassword123!"

Google Cloud SQL for PostgreSQL

On Google Cloud Platform, password resets for existing PostgreSQL database users can be initiated through the Cloud Console or using the gcloud SDK:

gcloud sql users set-password postgres --instance=my-instance-name --password="NewAdminPassword123!"

Comparing PostgreSQL Password Reset Methods

The following table summarizes the different recovery methods, their operational prerequisites, service impacts, and recommended implementation scenarios:

Recovery Method System Prerequisites Service Downtime / Impact Security Risk Primary Use Case
ALTER ROLE / \password Active DBA connection or CREATEROLE privileges None (Zero downtime) Very Low Routine user password rotations and developer access management.
Linux peer Auth Switching OS user access to postgres account via sudo None (Zero downtime) Low Password resets when local host shell access is available.
pg_hba.conf Modification (trust) Root / Administrator shell access on database host Configuration reload required (No cluster restart needed) High during temporary trust window Full lock-out recovery for self-hosted database servers.
Cloud Provider Console / CLI Cloud IAM permissions (rds:ModifyDBInstance, etc.) None (Managed control plane change) Low Password recovery on managed cloud instances (AWS RDS, Azure, GCP).

Troubleshooting Common Password Reset Issues

Even after issuing a password update command, database connection attempts can fail due to configuration mismatches, caching, or networking policies.

Client Authentication Failures (FATAL: password authentication failed)

If PostgreSQL continues to reject your connection attempt immediately after a password reset, check the following potential causes:

  • Password Hashing Algorithm Mismatch: Check the password_encryption parameter inside postgresql.conf. If the parameter was recently changed from md5 to scram-sha-256, existing password hashes may be incompatible until re-encrypted.
  • Target Database Rules in pg_hba.conf: The pg_hba.conf file parses rules sequentially from top to bottom. If a matching rule higher up in the file uses an unexpected authentication method, PostgreSQL applies that rule instead of subsequent ones. Use SHOW hba_file; within SQL to verify the configuration file path being evaluated.
  • Connection Strings and Connection Pools: Third-party application middleware and connection poolers (such as PgBouncer) maintain persistent backend connections. After updating a password, restart or reload your connection pooler service so it drops stale credentials.

MUST BE SUPERUSER TO ALTER USER Permission Errors

If a database user attempts to reset another user's credential and receives a permission denied error, the executing account lacks sufficient system authority. Ensure the account performing the change either has the SUPERUSER attribute or explicit privileges:

ALTER ROLE admin_user WITH CREATEROLE;

Password Cleanliness and Cleartext Leakage

If password statements were inadvertently run in cleartext SQL queries via terminal scripts or continuous integration pipelines, credentials may be logged to history files or central logging dashboards.

Clear local shell history files if sensitive strings were exposed:

history -c

rm ~/.psql_history

Best Practices for Database Access Management

Maintaining secure credentials and administrative controls reduces the need for emergency password resets and protects against unauthorized access.

Adopt SCRAM-SHA-256 Authentication

Older PostgreSQL installations often defaulted to md5 password hashing. Modern PostgreSQL environments should enforce scram-sha-256, which provides mutual authentication and challenge-response security that protects against password sniffing and replay attacks.

To enforce SCRAM authentication across your cluster, set the following entry in postgresql.conf:

password_encryption = scram-sha-256

Then verify that all entries in pg_hba.conf specify scram-sha-256 instead of md5.

Separate Administrative Roles

Avoid using the primary postgres superuser account for routine application queries or standard administrative tasks. Create individual dedicated roles with minimal required privileges using Role-Based Access Control (RBAC):

CREATE ROLE application_user WITH LOGIN PASSWORD 'strong_unique_password';

GRANT SELECT, INSERT, UPDATE ON ALL TABLES IN SCHEMA public TO application_user;

Implement Secret Rotation and IAM Integration

For modern enterprise workloads, manual password resets should be replaced with automated secret management infrastructure. Tools such as HashiCorp Vault, AWS Secrets Manager, or Azure Key Vault can rotate database passwords automatically on defined schedules. Where possible, integrate database access with centralized identity providers using IAM authentication, Kerberos, or mutual TLS (mTLS) certificates to eliminate long-lived passwords entirely.

Next Steps for Securing PostgreSQL Credentials

After completing a password reset, perform the following validation steps to ensure your database environment remains secure and operational:

  1. Verify Connections: Test all application services, background jobs, and developer client tools to confirm they can connect using the updated credentials.
  2. Audit Administrative Roles: Run \du within psql or query SELECT rolname, rolsuper, rolcreaterole FROM pg_roles; to confirm that superuser privileges are limited to authorized accounts.
  3. Audit Log Settings: Check your database logging configuration in postgresql.conf (log_connections, log_disconnections, and log_statement) to ensure credential changes and login attempts are tracked without logging plain-text passwords.
  4. Secure Configuration Files: Restrict access permissions on pg_hba.conf and postgresql.conf at the operating system level so only the postgres OS user and root can modify database access rules: sudo chmod 600 /etc/postgresql/16/main/pg_hba.conf

FAQs

What is the difference between ALTER USER and ALTER ROLE in PostgreSQL?

In PostgreSQL, USER is a syntax alias for ROLE. Executing ALTER USER username WITH PASSWORD '...'; performs the exact same operation as ALTER ROLE username WITH PASSWORD '...';. The unified role model handles all authorization concepts, where a role with the LOGIN privilege represents a standard user account.

Why does PostgreSQL return a password authentication failed error after resetting the password?

This error usually occurs when client applications connect through an external connection pooler (like PgBouncer) that caches old credentials, when pg_hba.conf matches an earlier rule using a different authentication method, or when special characters in the new password are unescaped in application connection strings.

How do I change a user password without storing it in shell history?

Use the internal psql interactive meta-command \password username. This prompts you for the password in an interactive input field that masks your typing and prevents cleartext password strings from being recorded in .bash_history or .psql_history.

Can I reset a PostgreSQL password without restarting the database engine?

Yes. Changing a user password via ALTER ROLE or \password takes effect immediately across the cluster without requiring a server reload or restart. If you must use the pg_hba.conf recovery method, reloading the configuration via systemctl reload postgresql or SELECT pg_reload_conf(); applies the change without dropping active client connections or causing database downtime.

What should I do if the postgres system user password is forgotten on a Linux server?

If you have root or sudo permissions on the Linux host, switch to the postgres system user via sudo -i -u postgres and run psql. Because default local configurations use peer authentication, this gives you instant superuser SQL access to run ALTER ROLE postgres WITH PASSWORD 'new_password'; without needing the old password or editing configuration files.

EDITORIAL CATEGORY METADATA:

Written by

Andrew Miller

Personal Finance & Banking Reporter