トップページへ

「psql: FATAL: Peer authentication failed for user "postgres"」が表示された場合の対処

小粋空間 » Movable Type » PostgreSQL » 「psql: FATAL: Peer authentication failed for user "postgres"」が表示された場合の対処

「psql: FATAL: Peer authentication failed for user "postgres"」が表示された場合の対処について紹介します。

1.はじめに

LinuxでPostgreSQLを起動して"hoge"というデータベースを作成しました。

# su - postgres
-bash-4.2$ createdb --owner postgres hoge
-bash-4.2$ exit

次にpsqlで接続しようとしたところ、「psql: FATAL: Peer authentication failed for user "postgres"」をいうエラーに遭遇しました。

# psql -q -U postgres -d hoge
psql: FATAL:  Peer authentication failed for user "postgres"

ちなみにpostgresユーザーで接続すればOKになります。

# su - postgres
最終ログイン: 2020/05/21 (木) 10:39:57 JST日時 pts/4
-bash-4.2$ psql -q -U postgres -d hoge
hoge=#

Linuxユーザーから直接接続する方法がわかりません。

ということで、「psql: FATAL: Peer authentication failed for user "postgres"」が表示された場合の対処について紹介します。

2.原因

postgresのhba (host base authentication) 機能で、peer認証がオンになっているためです。

peer認証では、ローカルからのアクセスはLinuxのユーザーとパスワードがpostgresのものと同じでないとエラーになるようです

3.対処方法

ここではローカルアクセスのpeer認証をオフにする方法を示します。

peer認証を設定しているファイル「pg_hba.conf」を探します。

# find / -print |grep pg_hba.conf
./var/lib/pgsql/data/pg_hba.conf

vimで開きます。

# vim /var/lib/pgsql/data/pg_hba.conf

「local」の行の一番右側が「peer」担っていると思います。

# TYPE  DATABASE        USER            ADDRESS                 METHOD
 
# "local" is for Unix domain socket connections only
local   all             all                                     peer
# IPv4 local connections:
host    all             all             127.0.0.1/32            ident
# IPv6 local connections:
host    all             all             ::1/128                 ident

これを「trust」に変更します。「trust」は接続を無条件で許可することを意味します。

# TYPE  DATABASE        USER            ADDRESS                 METHOD
 
# "local" is for Unix domain socket connections only
local   all             all                                     trust
# IPv4 local connections:
host    all             all             127.0.0.1/32            ident
# IPv6 local connections:
host    all             all             ::1/128                 ident

編集後、postgresqlを再起動。

# service postgresql restart
Redirecting to /bin/systemctl restart postgresql.service

これで下記のようにLinuxユーザーから直接接続できるようになります。

# psql -q -U postgres -d hoge
hoge=#

4.参考サイト

参考サイトは下記です。ありがとうございました。