koheitakahashiのブログ

2020.07.01にプログラマーとして生を受けた私が学んだことや、日常について徒然に書いていきます。

postgresqlが立ち上がらなくなった時の解決方法

データベースの操作を学習しようと、postgresを起動したところ、以下のようなエラーが出てしまい、何時間も悩んでしまったので、その解決方法を自分が忘れないようにまとめます💪

自分の環境

サーバー

  • さくらVPS
  • Debian 9.9
  • postgresql 11.5

クライエント

  • mac os Mojave バージョン10.14.6
  • ターミナル

起った問題

直前まで普通に立ち上がっていた、psqlが急に立ち上がらなくなり、以下のエラーが出ました。

出現したエラー

psql: 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"?

エラーがでた手順

  1. クライエントで、psql -U ユーザー名 -d postgres -h ホスト名でpsqlを立ち上げて、CREATE DATEBASE shopという学習用のshopというデータベースを作成したあと、一度、\qで終了しました。

  2. その後、psql -U ユーザー名 -d shop -h ホスト名でpostgresを立ち上げようとしたところ、上記の出現したエラーが出て、立ち上がらなくなってしまいました。

解決した手順

PostgreSQL で psql コマンド を実行したら could not connect to database postgres: could not connect to server: No such file or directory と出る場合の手順を参考にしました。

1. pg_lsclusterで状況を確認する。

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

このコマンドは、すべてのクラスタの設定と状態に関する情報を表示します。

2. pg_ctlcluster ~ startでクラスタを開始させてみます。

ここで、~の中には、1のvarclusterの値が入ります。

$ pg_ctlcluster 11 main start
Warning: the cluster will not be running as a systemd service. Consider using systemctl:
  sudo systemctl start postgresql@11-main
Error: /usr/lib/postgresql/11/bin/pg_ctl /usr/lib/postgresql/11/bin/pg_ctl start -D /var/lib/postgresql/11/main -l /var/log/postgresql/postgresql-11-main.log -s -o  -c config_file="/etc/postgresql/11/main/postgresql.conf"  exited with status 1: 

今回、エラーが出され、ログが出力されました。そのログを見てみると・・・FATALを発見❗️

2019-09-12 07:36:01.788 JST [988] FATAL:  could not load pg_hba.conf

つまりは、pg_hba.confが読み込めてないとのこと。これでエラーの原因がわかりました。

3. could not load pg_hba.confの解決方法を調べる。

could not load pg_hba.conf でハマったがヒット。これを参考にして以下のように、pg_hba.confを編集します。

$ vi /etc/postgresql/11/main/pg_hba.conf

開いたら、90行目に以下の項目があるので、自分のクライエントのIPアドレスの後ろに/32をつければ完了。 私はここに/32をつけていなかったのでした😱今回のエラーの原因はここにあったようです。

# IPv4 local connections:
host    all             all             IPアドレス             md5
host    all             all             自分のIPアドレス       md5
  1. 実際に動くか、pg_ctlcluster 11 main startでチェック。

無事エラーは出されずに動いた❗️

$ pg_ctlcluster 11 main start
Warning: the cluster will not be running as a systemd service. Consider using systemctl:
  sudo systemctl start postgresql@11-main
Cluster is already running.

まとめ

今回、データベースの操作を学習するためにpostgresを起動したのですが、最初でこのようにはまってしまって、結局半日以上時間を使ってしまいました💦 でも、なんとか、エラーが解決したので、データベースの操作を学んでいきます💪

参考サイト

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

資料編:Ubuntu特有のPostgreSQL用コマンド

could not load pg_hba.conf でハマった