Problem: Sometimes, we get the following error when trying to make a connection in Rails.
FATAL ERROR: Peer authentication failed for user "postgres"
Solution: There are a lot of solutions described below.
To changing pg_hba.conf file
Change the following line
local all postgres peer |
To
local all postgres md5 |
After altering the file, you have to restart your PostgreSQL service.
If you are on Linux, then use the following command.
$ sudo service postgresql restart |
For Windows
Window--> Services--> PostgreSQL-x64-12--> Right clieck cand choose Re-Start option |
If still, you are facing the same fatal error, then see the following solution.
1- Open the file pg_hba.conf (Location : /etc/postgresql/9.x/main)
2- Change the line
local all postgres peer |
local all postgres trust |
For Linux, use the following command
$ sudo service postgresql restart |
Window--> Services--> PostgreSQL-x64-12--> Right clieck cand choose Re-Start option |
$ psql -U postgres db> ALTER USER postgres with password 'your-pass'; |
Finally, change the pg_hba.conf from
local all postgres trust |
To
local all postgres md5 |
trust - No authorization anyone can access the database. Make sure don't leave the pSQL at this mode.
peer - Peer client operating system with the database user name to access it.
md5 - Authorized, Protected by password
Using the Command
If you don't want to change the config file(pg_hba.conf), try the following command to fix the issue.
root# su postgres postgres$ psql -U postgres psql (9.3.6) Type "help" for help. postgres=#\password Enter new password: Enter it again: postgres=# |
Or use the following
sudo psql --host=localhost --dbname=database-name --username=postgres |
Also, try the following code in the connection.
Use host=localhost in connection. PGconn *conn = PQconnectdb( "host=localhost user=postgres dbname=postgres password=123" ); |