PostgreSQL Peer Authentication Failed Fix
Install PostgreSQL:
Ubuntu/Debian:
sudo apt update
sudo apt install postgresql postgresql-contrib -y
Check if PostgreSQL is running:
sudo systemctl status postgresql
Start it if needed:
sudo systemctl start postgresql
Enable auto-start:
sudo systemctl enable postgresql
Trying this usually fails:
psql -U postgres
FATAL: Peer authentication failed for user "postgres"
This happens because PostgreSQL uses peer authentication by default on local connections. This means Linux user must match PostgreSQL user, If your Linux session user is ex-introvert and you try connecting as postgres, PostgreSQL rejects the connection.
Temporary solution:
sudo -u postgres psql
This switches to the Linux postgres user before opening PostgreSQL.
Set a password for postgres:
ALTER USER postgres PASSWORD 'yourpassword';
\q
Open PostgreSQL authentication config:
sudo nano /etc/postgresql/[Version_number]/main/pg_hba.conf
[Version_number] may differ, check it manually with < ls /etc/postgresql/ > or use tab for auto completion Find this line:
local all postgres peer
change it to :
local all postgres md5
You may also find:
local all all peer
change it to :
local all all md5
Save the file and Restart PostgreSQL:
sudo systemctl restart postgresql
Now connect using:
psql -U postgres -W
-W forces password authentication.
You should now connect successfully.
Frequently Asked Questions
Why does PostgreSQL use peer authentication by default?+
Peer authentication is designed for local Linux systems where the operating system user is trusted. It avoids password prompts for matching system users but becomes confusing during manual setup or application development.
What does “Peer authentication failed for user postgres” mean?+
It means the current Linux user does not match the PostgreSQL user being requested. PostgreSQL checks the operating system identity before allowing access.
Is md5 authentication better than peer authentication?+
md5 is more practical for development and remote connections because it uses passwords. Peer authentication is mainly useful for tightly controlled local environments.
Why does psql work with sudo -u postgres psql?+
Because the command switches the current Linux session to the postgres system user, matching PostgreSQL's expected peer-authenticated identity.
Where is the pg_hba.conf file located?+
/etc/postgresql/<version>/main/pg_hba.conf The PostgreSQL version directory depends on the installed version.
Why must PostgreSQL be restarted after changing pg_hba.conf?+
Authentication settings are loaded into memory. Restarting or reloading PostgreSQL applies the new authentication configuration.
