ryotatake blog

Webエンジニア

PostgreSQL - FATAL: Peer authentication failed for user "user_name" と表示されたときの解決法

Ruby on Rails 5 速習実践ガイド』Chapter 6を進めていて、「FATAL: Peer authentication failed for user "user_name"」のエラーが出て詰まったので解決策をまとめます。

環境

起きていた問題

PostgreSQLで‘taskleaf‘というユーザーを作成した後にこのユーザーでデータベースを作成しようとすると、「FATAL: Peer authentication failed for user "taskleaf"」と出て失敗しました。

$ RAILS_ENV=production bin/rails db:create db:migrate
FATAL:  Peer authentication failed for user "taskleaf"
Couldn't create 'taskleaf_production' database. Please check your configuration.
rails aborted!
PG::ConnectionBad: FATAL:  Peer authentication failed for user "taskleaf"
/home/vagrant/app/rails/taskleaf/bin/rails:9:in `<top (required)>'
/home/vagrant/app/rails/taskleaf/bin/spring:15:in `<top (required)>'
bin/rails:3:in `load'
bin/rails:3:in `<main>'
Tasks: TOP => db:create
(See full trace by running task with --trace)

解決策

psqlがPeer authentication failedというエラーで起動できない - QA@ITを参考にさせていただきました。

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

peer認証では、ユーザ名がUnixのユーザ名と一致していないとエラーになります。

http://www.postgresql.jp/document/9.1/html/auth-methods.html#AUTH-PEER


pg_hba.conf (私の環境では /etc/postgresql/9.1/main/ 以下にありました) を確認します。

local all postgres peer

例えば上記の行を以下のように変更してpostgresqlを再起動することで、Unixのpostgresユーザ以外でもpostgresユーザでログインできるようになります。

local all postgres md5

ここに書いてある通りなのですが、

pg_hba.confを編集して、

local  all    all   peer

local  all    all   md5

にしてから、PostgreSQLを再起動すれば解決します。

※ CentOS7でPostgreSQLの再起動

$ systemctl restart postgresql.service

困ったこと

pg_hba.confの場所が分からない

pg_hba.confの場所は以下の二つの方法で調べることができました。

findを使って探す

$ sudo find / -name pg_hba.conf
/var/lib/pgsql/data/pg_hba.conf

postgresqlに入ってshow hba_file;で調べる

$ psql postgres
psql (9.2.24)
Type "help" for help.

postgres=# show hba_file;
            hba_file
---------------------------------
 /var/lib/pgsql/data/pg_hba.conf
(1 row)

pg_hba.confの場所にファイルが見つからない

ファイルの場所は分かったのですが、以下のようにしてファイルを編集しようとしても、新しいファイルが開かれてしまいました。

$ vim /var/lib/pgsql/data/pg_hba.conf  # pgsql以降はtabによる補完も効かない

原因はpgsqlディレクトリ内で権限が足りないことでした。sudoをつけることで正しいファイルを開いて編集することができました。

$ sudo vim /var/lib/pgsql/data/pg_hba.conf