Ошибка peer authentication failed for user postgres

pg_config is for compliation information, to help extensions and client programs compile and link against PostgreSQL. It knows nothing about the active PostgreSQL instance(s) on the machine, only the binaries.

pg_hba.conf can appear in many other places depending on how Pg was installed. The standard location is pg_hba.conf within the data_directory of the database (which could be in /home, /var/lib/pgsql, /var/lib/postgresql/[version]/, /opt/postgres/, etc etc etc) but users and packagers can put it wherever they like. Unfortunately.

The only valid ways find pg_hba.conf is to ask a running PostgreSQL instance where it’s pg_hba.conf is, or ask the sysadmin where it is. You can’t even rely on asking where the datadir is and parsing postgresql.conf because an init script might passed a param like -c hba_file=/some/other/path when starting Pg.

What you want to do is ask PostgreSQL:

SHOW hba_file;

This command must be run on a superuser session, so for shell scripting you might write something like:

psql -t -P format=unaligned -c 'show hba_file';

and set the environment variables PGUSER, PGDATABASE, etc to ensure that the connection is right.

Yes, this is somewhat of a chicken-and-egg problem, in that if the user can’t connect (say, after screwing up editing pg_hba.conf) you can’t find pg_hba.conf in order to fix it.

Another option is to look at the ps command’s output and see if the postmaster data directory argument -D is visible there, e.g.

ps aux  | grep 'postgres *-D'

since pg_hba.conf will be inside the data directory (unless you’re on Debian/Ubuntu or some derivative and using their packages).

If you’re targeting specifically Ubuntu systems with PostgreSQL installed from Debian/Ubuntu packages it gets a little easier. You don’t have to deal with hand-compiled-from-source Pg that someone’s initdb’d a datadir for in their home dir, or an EnterpriseDB Pg install in /opt, etc. You can ask pg_wrapper, the Debian/Ubuntu multi-version Pg manager, where PostgreSQL is using the pg_lsclusters command from pg_wrapper.

If you can’t connect (Pg isn’t running, or you need to edit pg_hba.conf to connect) you’ll have to search the system for pg_hba.conf files. On Mac and Linux something like sudo find / -type f -name pg_hba.conf will do. Then check the PG_VERSION file in the same directory to make sure it’s the right PostgreSQL version if you have more than one. (If pg_hba.conf is in /etc/, ignore this, it’s the parent directory name instead). If you have more than one data directory for the same PostgreSQL version you’ll have to look at database size, check the command line of the running postgres from ps to see if it’s data directory -D argument matches where you’re editing, etc.
https://askubuntu.com/questions/256534/how-do-i-find-the-path-to-pg-hba-conf-from-the-shell/256711

Solution of psql: FATAL: Peer authentication failed for user “postgres” (or any user)

The connection failed because by default psql connects over UNIX sockets using peer authentication, that requires the current UNIX user to have the same user name as psql. So you will have to create the UNIX user postgres and then login as postgres or use sudo -u postgres psql database-name for accessing the database (and psql should not ask for a password).

If you cannot or do not want to create the UNIX user, like if you just want to connect to your database for ad hoc queries, forcing a socket connection using psql --host=localhost --dbname=database-name --username=postgres (as pointed out by @meyerson answer) will solve your immediate problem.

But if you intend to force password authentication over Unix sockets instead of the peer method, try changing the following pg_hba.conf* line:

from

# TYPE DATABASE USER ADDRESS METHOD
local  all      all          peer

to

# TYPE DATABASE USER ADDRESS METHOD
local  all      all          md5
  • peer means it will trust the identity (authenticity) of UNIX user. So not asking for a password.

  • md5 means it will always ask for a password, and validate it after hashing with MD5.

  • trust means it will never ask for a password, and always trust any connection.

You can, of course, also create more specific rules for a specific database or user, with some users having peer and others requiring passwords.

After changing pg_hba.conf you’ll need to restart PostgreSQL if it’s running. E.g. sudo service postgresql restart

Steps to change/create default postgres user’s password:
  1. trust connection by adding in pg_hba.conf file
  • local all postgres trust
  1. Restart postgresql service
  • sudo service postgresql restart
  1. psql -U postgres

  2. At the postgres=# prompt, change the user name postgres password:

  • ALTER USER postgres with password ‘new-password’;
  1. Revert the changes in pg_hba.conf file from trust to md5 and restart postgresql.
pg_hba.conf file location

The file pg_hba.conf will most likely be at /etc/postgresql/9.x/main/pg_hba.conf
To check location of pg_hba.conf connect to postgres db using psql then type SHOW hba_file; command.

After change pg_hba.conf file, you can execute SELECT pg_reload_conf(); or pg_ctl reload with superuser instead of restart postgresql service.

* Source

Peer authentication failed error arrives when you try to login to your PostgreSQL user but authentication fails because by default psql connects over UNIX sockets using peer authentication instead of password authentication.

In this article we will learn how to get rid of FATAL: Peer authentication failed for user «postgres» error by enforcing password authentication over Unix sockets peer method,

First, navigate to the /etc/postgresql/10/main directory.

cd /etc/postgresql/10/main

Note that 10 is the PostgreSQL version it can be different for you.

Here resides the pg_hba.conffile we need to do some changes here you may need sudo access for this.

sudo nano pg_hba.conf

Scroll down the file till you find this —

# Database administrative login by Unix domain socket
local   all             postgres                                peer

Here change the peer to md5 as follows.

# Database administrative login by Unix domain socket
local   all             postgres                                md5
  • peer means it will trust the authenticity of UNIX user hence does not prompt for the password.
  • md5 means it will always ask for a password, and validate it after hashing with MD5.

Now save the file and restart the Postgres server.

sudo service postgresql restart

And that’s it!

Try to log in now.

sudo -u postgres psql
Password:
postgres=#

WEB DEVELOPMENT

In this tutorial, we will see how we can resolve the error “FATAL: Peer authentication failed for user *” in PostgreSQL. It is super simple to resolve this issue which takes a maximum of ten minutes. So without wasting time, let’s get started!

Reason Behind the Peer authentication failed Error

First of all, it is very important to understand the reason behind getting the error “FATAL: Peer authentication failed for user”. Before that, let’s see what a peer connection means in PostgreSQL.

When you install PostgreSQL on Linux/Ubuntu and other UNIX-like operating systems, the system automatically creates a user with the name postgres. Now you might be thinking, hey, what this user has to do with the PostgreSQL server? Let me tell you.

When you try to log in to the PostgreSQL client using the command sudo -u postgres psql , it checks if there is a user present on your OS having the username you entered, in our case- postgres. If yes then it will not ask you to enter a password and you will get logged in automatically. But, if the username you are logging in with is not present as an OS user, you will get an error that the user is not present.

Automatic Login

Automatic Login

This type of authentication is called a peer login method. In this method, there is no password set by default when you install the PostgreSQL server. Only a user of the name postgres is created.

Now let’s see the reason for getting this error.

As said earlier, the username postgres is created by PostgreSQL without any password. It uses the peer connection method for logging you into the PostgreSQL client. However, when you try to login into your PostgreSQL client using the command psql -U postgres, PostgreSQL will need you to log in using the password because it will not check the OS user of the same name this time. This is because PostgreSQL client authentication for the user postgres is set to the peer connection login method.

Peer Authentication Failed

Peer Authentication Failed

The login settings are present in the client authentication configuration file. We need to change the settings in order to let our user log in using the password.

So, let’s do that.

Step 1- Set or Change the password

If you have freshly installed the PostgreSQL setup and didn’t set up the password yet, you can follow the steps below to set the password.

If you have already set up the password but now don’t remember it, you can follow the same procedure.

  • First, log in to the PostgreSQL client using the peer connection method. For this, type the command and enter the password of your OS user (because we are using the sudo command)-
sudo -u postgres psql

Login To The Postgresql Client

Login To The Postgresql Client
  • Note that, -u is in the small case. Here, this command will first switch the user to postgres and then enable the psql client. This way, you will automatically be logged in to the PostgreSQL client.
  • Now enter the following command to set/change the password for the user of PostgreSQL, in our case, the username is postgres.
password postgres

Set The Password

Set The Password
  • The password has been successfully set/changed. Now we can get out of PostgreSQL using the q command and go to the next step, which is updating the configuration settings of the client authentication.

Step 2 – Update Client Authentication Configuration Settings

All the client authentication configurations are present in the pg_hba.conf file which is generally located in the /etc/postgresql/[version]/main/ or /var/lib/pgsql/data/pg_hba.conf directory. However, you can use the locate pg_hba.conf command to locate the file.

Now open the file using any GUI text editor or a CLI text editor such as nano. Here, I am going to use the nano. I will enter the command sudo nano /etc/postgresql/14/main/pg_hba.conf to open the configuration file. You can use other editors also such as notepad, TextPad or Wordpad.

Scroll down to the end where you will see some configurations as shown in the image below.

Configuration

Configuration

Here, we need to change only one setting.

You can see there, the method for the user postgres is set to peer. We just need to change it to the md5.

Simply, change this-

local   all             postgres                                peer

to this-

local   all             postgres                                md5

Now you might be wondering what is md5. Let me tell you quickly.

There are three methods to log in.

  • peer  – means it will trust the identity (authenticity) of the UNIX users. So not asking for a password.
  • md5  – means it will always ask for a password, and validate it after hashing with MD5.
  • trust –  means it will never ask for a password, and always trust any connection

Set Login Method Md5

Set Login Method Md5

Step 3 – Restart the PostgreSQL Server

Now you are all set to use the password for logging in. You just need to restart the PostgreSQL server for changes to take place.

To restart the PostgreSQL server, use the command- sudo systemctl restart postgresql

That’s it. Now you can log in to the PostgreSQL client using the command psql -U postgres.

Login Using Password

Login Using Password

As you can see, now we can successfully log in to the client using the password.

Note that, you can now use both login methods- peer connection using the command sudo -u postgres psql and password using psql -U postgres. Don’t use -u and -U interchangeably here. Here, -u and -U have different meanings.

Conclusion

This is a quite an interesting topic because almost everyone who gets engaged with PostgreSQL as a beginner faces this problem. Not only on ubuntu but also in other programming languages/frameworks such as ruby on rails, you face this problem while connecting with the database. So, it is a quick and easy guide that may save you a lot of time.

Reference

Here is the StackOverflow thread on the same problem with multiple solutions. If our guide is not able to solve the error for you, this thread might help.

I just installed PostgreSQL 9.4 on Ubuntu 15.10.

  1. I created a user with createuser -P myuser
  2. I created a database with createdb -O myuser mydatabase
  3. I edited pg_hba.conf and added local mydatabase myuser md5
  4. I restarted PostgreSQL with sudo service postgresql restart

User myuser is a PostgresSQL user only and has no user account on Ubuntu.

When I try to connect to the database with psql -W mydatabase myuser it fails with psql: FATAL: Peer authentication failed for user "myuser".

PostgreSQL is running …

● postgresql.service - PostgreSQL RDBMS
   Loaded: loaded (/lib/systemd/system/postgresql.service; enabled; vendor preset: enabled)
   Active: active (exited) since Thu 2016-03-03 09:53:00 CET; 9min ago
  Process: 22219 ExecStart=/bin/true (code=exited, status=0/SUCCESS)
 Main PID: 22219 (code=exited, status=0/SUCCESS)

Mar 03 09:53:00 SERVER01 systemd[1]: Starting PostgreSQL RDBMS...
Mar 03 09:53:00 SERVER01 systemd[1]: Started PostgreSQL RDBMS.

… and listening.

Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 localhost:postgresql    *:*                     LISTEN
tcp6       0      0 localhost:postgresql    [::]:*                  LISTEN
Active UNIX domain sockets (only servers)
Proto RefCnt Flags       Type       State         I-Node   Path
unix  2      [ ACC ]     STREAM     LISTENING     151534   /var/run/postgresql/.s.PGSQL.5432

What do I have to do to connect with user myuser to database mydatabase?

Evan Carroll's user avatar

Evan Carroll

60.5k44 gold badges224 silver badges456 bronze badges

asked Mar 3, 2016 at 9:06

Daniel's user avatar

In a fresh install from a few days ago, the second line of my pg_hba.conf is

local   all             all              peer

I believe this is the one that makes your connection attempt fail.

The order of rules matter here: the first one that matches the access method, username, database name and source IP range will be considered. If it fails, then there is no second try, so the connection attempt will likely fail. Or, as the documentation states:

There is no «fall-through» or «backup»: if one record is chosen and the authentication fails, subsequent records are not considered. If no record matches, access is denied.

The solution is easy: either remove the above line if you don’t plan to use peer authentication, or move your specific rule above this one.

Evan Carroll's user avatar

Evan Carroll

60.5k44 gold badges224 silver badges456 bronze badges

answered Mar 3, 2016 at 9:16

dezso's user avatar

dezsodezso

30.4k13 gold badges98 silver badges143 bronze badges

2

First of all, check if you have the lines giving permission to the myuser user in pg_hba.conf. For example:

# IPv4 local connections:
host    all             all             127.0.0.1/32            md5
# IPv6 local connections:
host    all             all             ::1/128                 md5

Or any other lines of permission to IPV4 (and IPv6 if you use) with: TYPE DATABASE USER ADDRESS METHOD

After this check, run the psql as follows:

psql -h localhost -U myuser mydatabase

And then, the requested prompt, enter the user’s password myuser.

aakaasaraamanna's user avatar

answered Mar 4, 2016 at 14:52

Alvaro Neto's user avatar

2

Понравилась статья? Поделить с друзьями:
  • Ошибка php fatal error failed opening required
  • Ошибка pdl на принтере xerox
  • Ошибка php fatal error allowed memory size of
  • Ошибка package does not exist
  • Ошибка php failed to open stream