問題
Rails で bin/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"?
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
参考
- PostgresSQL のerror Postgres PG::ConnectionBad: 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"? - Qiita
- 【再起動して解決】connections on Unix domain socket "/tmp/.s.PGSQL.5432"?への対処 | ベランダゴーヤ研究所
- Postgresqlに接続できなくなった時 - Qiita
- ruby on rails - Postgres could not connect to server - Stack Overflow