Ensure you have access to the server where the PostgreSQL database is hosted.
Edit the PostgreSQL configuration file pg_hba.conf
to temporarily allow password-free login. This file is often located in /etc/postgresql/[version]/main/
or /var/lib/postgresql/[version]/data/
.
# Example path to edit pg_hba.conf sudo vim /etc/postgresql/[version]/main/pg_hba.conf
Change the authentication method from md5
or scram-sha-256
to trust
for local connections:
# TYPE DATABASE USER ADDRESS METHOD local all postgres trust host all postgres 127.0.0.1/32 trust
Reload the PostgreSQL service to apply these changes:
sudo systemctl reload postgresql
Log in without a password and set a new one:
psql -h localhost -U postgres
Once logged in, execute:
ALTER USER postgres WITH PASSWORD 'new_password';
Replace 'new_password'
with a secure password of your choice.
Revert your changes in the pg_hba.conf
file from trust
back to md5
or scram-sha-256
.
sudo vim /etc/postgresql/[version]/main/pg_hba.conf
Reload the PostgreSQL server to enforce the new password settings:
sudo systemctl reload postgresql
After completing these steps, you should be able to log in to the PostgreSQL server with the postgres
user using the new password.