PostgreSQL で psql コマンド を実行したら could not connect to database postgres: could not connect to server: No such file or directory と出る場合

状況

$ psql を実行すると無情に以下のようなエラーが出続けるという状況です*1

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

注意

十中八九、エラーメッセージに書かれているソケットが原因ではないです。後述するように、各種設定がおかしいです*2

再インストールやサービスのリスタートをしても、見た目は正常に動いているように見えてしまう*3のがとても厄介で、めちゃくちゃハマりました。

そして結論

Stack Overflow にあるとおりです。

具体的な結論

具体的に結論を説明します。なお、以下はすべて sudo で実行することを前提としています。

1. pg_lsclusters を実行して現状を確認する。

# pg_lsclusters
Ver Cluster Port Status Owner    Data directory              Log file
10  main    5432 down   postgres /var/lib/postgresql/10/main /var/log/postgresql/postgresql-10-main.log

上記の結果の、VerClusterLog file の値を後で使います。Statusdown となっているので psql コマンド でエラーが出るのは当然と言えます。

2. cluster を start させてみる

以下のコマンドで cluster を start させてみます。なお、実行するコマンドのオプションには「1.」の VerCluster の値を用います。最後に start を付与します。

もし start できたならば psql コマンド が正常に実行できますのでここで終わりです。が、おそらく何らかのエラー(例えば以下のような)が吐き出されるでしょう。

# pg_ctlcluster 10 main start
Job for postgresql@10-main.service failed because the service did not take the steps required by its unit configuration.
See "systemctl status postgresql@10-main.service" and "journalctl -xe" for details.

3. エラーログを確認する

「2.」で出たエラーの詳細はエラーログに書き出されています。エラーログの場所は「1.」の Log file の場所です。

# cat /var/log/postgresql/postgresql-10-main.log

ログがエラーの原因についてのすべてを語ってくれています。

  • 例1
2018-10-26 20:24:55.208 GMT [12282] LOG:  unrecognized configuration parameter "listen_address" in file "/etc/postgresql/10/main/postgresql.conf" line 59
2018-10-26 20:24:55.208 GMT [12282] FATAL:  configuration file "/etc/postgresql/10/main/postgresql.conf" contains errors
pg_ctl: could not start server
Examine the log output.
  • 例2
2018-10-27 05:43:45 JST [8391-1] FATAL:  private key file "/etc/ssl/private/ssl-cert-snakeoil.key" has group or world access
2018-10-27 05:43:45 JST [8391-2] DETAIL:  File must have permissions u=rw (0600) or less if owned by the database user, or permissions u=rw,g=r (0640) or less if owned by root.

「例1」では postgresql.conf の書式に誤りがあることが指摘されています。「例2」では鍵ファイルのパーミッションが適切でないことが指摘されています。

4. エラーを修正して再度 cluster を start させる

「3.」のエラーを修正したら PostgreSQL のサービスを再起動し*4、再び pg_ctlcluster コマンドを実行しましょう。

# pg_ctlcluster 10 main start

特にエラーが吐き出されなければ、これで psql コマンド が通常通り使えるようになったはずです。

混乱させられる点(繰り返します)

再インストールやサービスのリスタートをしても、見た目は正常に動いているように見えてしまう*5のがとても厄介で、めちゃくちゃハマりました*6

*1:環境や状況によってエラーメッセージは微妙に違います

*2:か、単なるサーバ起動し忘れ

*3:サービスは起動する

*4:sudo service postgresql restart などを実行する

*5:サービスは起動する

*6:dry-run コマンドってないんでしょうか……

Powered by はてなブログ