The error FATAL: Peer authentication failed for user "db_user" indicates that PostgreSQL is trying to authenticate the user db_user using "peer" authentication, but it is failing.
What is Peer Authentication?
Peer authentication is a method used by PostgreSQL to authenticate users based on the Unix/Linux user they are currently logged in as. This means PostgreSQL expects the database username to match the system username.
Solutions to Resolve the Error
1. Switch to Password Authentication
You can change the authentication method to md5 (password-based) or password by modifying the pg_hba.conf file, which is the PostgreSQL configuration file for client authentication.
-
Locate the
pg_hba.conffile:- The location of the
pg_hba.conffile can vary, but it is typically found in/etc/postgresql/<version>/main/on Debian-based systems or/var/lib/pgsql/<version>/data/on RedHat-based systems.
- The location of the
You can locate it using the find command:
sudo find / -name "pg_hba.conf"
-
Edit the
pg_hba.conffile:- Open the file in a text editor:
sudo nano /etc/postgresql/<version>/main/pg_hba.conf
-
Change the Authentication Method:
- Look for the line that reads something like this:
local all all peer
- Change
peertomd5orpasswordso it looks like this:
local all all md5
- Save the file and exit the editor.
-
Restart PostgreSQL:
- After making changes to the
pg_hba.conffile, restart the PostgreSQL service:
- After making changes to the
sudo systemctl restart postgresql
-
Try Connecting Again:
- Now, try connecting again, and it should prompt you for a password:
psql -U db_user -d db_name
2. Use the Correct Unix/Linux User
If you prefer to use peer authentication, ensure that you are logged in as the Unix/Linux user db_user. You can switch to the db_user user using the following command:
su - db_user
After switching to the db_user user, try connecting to the database again:
psql -d road_sim
3. Specify a Different Authentication Method Just for Your User
You can also configure the pg_hba.conf file to specify md5 authentication just for the db_user user:
-
Edit the
pg_hba.conffile:- Add a line above the existing entries in the
pg_hba.conffile:
- Add a line above the existing entries in the
local db_name db_user md5
- Save the file and restart PostgreSQL.
-
Set a Password for the User:
- If you haven't set a password for the
db_useruser, you can do so with:
- If you haven't set a password for the
ALTER USER db_user WITH PASSWORD 'your_password';
Therefore ...
-
Switch to password-based authentication by modifying the
pg_hba.conffile and setting it tomd5orpassword. - Use the correct Unix/Linux user that matches the PostgreSQL user to maintain peer authentication.
-
Configure user-specific authentication in
pg_hba.conf.
If you found this article helpful, consider supporting me by buying me a coffee. Your support encourages me to continue creating valuable content. Thank you!
Try these solutions, and you should be able to connect successfully.

Top comments (0)