Just do IT

思うは招く

Unix domain socket "/tmp/.s.PGSQL.5432"? エラーで Postgres に接続できないときの対処

問題

Railsbin/rails sをしてサーバーを起動しようとすると、以下のエラーが出て Postgres が動かない。

could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/tmp/.s.PGSQL.5432"?

Postgres に接続もできない。

$ psql -l
psql: error: could not connect to server: could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/tmp/.s.PGSQL.5432"?

psql

bin/rails db:createをしても同様のエラーが表示されてDBが作成されない。

このケースに何度も遭遇しているため、解決策がいくつかある。

解決1

postmaster.pid ファイルを削除したら接続できるようになった。

rm /usr/local/var/postgres/postmaster.pid

ruby on rails - Postgres could not connect to server - Stack Overflow」からの引用。

Had a similar problem; a pid file was blocking postgres from starting up. To fix it:

rm /usr/local/var/postgres/postmaster.pid

and then all is well.

おそらく、Postgres が正常に終了していなかったために pid ファイルが残っていたのがこのケースの理由。

解決2:ポスグレのアップグレード

Rubyを2.7.3、Railsを6.1.3.1に上げてポスグレが動かなくなった(というか接続できなくなった)ときに以下を実行したら解決した。

$ brew upgrade postgresql
==> Upgrading postgresql 13.1 -> 13.2_1

他にも試せること

ポスグレを再起動する。

$ brew services restart postgresql

参考