PostgreSQLをlocalhost以外から接続するための設定メモです。

参考になるページは次の通り。

18.3. 接続と認証 | PostgreSQL 9.4.5文書
https://www.postgresql.jp/docs/9.4/runtime-config-connection.html

19.1. pg_hba.confファイル | PostgreSQL 9.4.5文書
https://www.postgresql.jp/docs/9.4/auth-pg-hba-conf.html

全体の流れは、次のようになります。

  • 接続用ユーザの作成
  • サーバへの接続設定
  • クライアント認証の設定

ゴールとしては、次のようにpsqlコマンドで、
localhost以外から、接続できるようにすることです。

$ psql --host=<PostgreSQLのIPアドレス> -d <DB名> -U <PostgreSQLのユーザ名>

確認した環境は、PostgreSQL14.17・UbuntuLinux22.04です。

$ psql --version
psql (PostgreSQL) 14.17 (Ubuntu 14.17-0ubuntu0.22.04.1)

接続用ユーザの作成

まずは接続用のユーザを作成します。

PostgreSQLを動かすサーバで、以下のコマンドを実行します。

$ sudo su postgres -c psql
> CREATE USER <PostgreSQLのユーザ名> WITH PASSWORD '<パスワードの指定>';
> GRANT ALL PRIVILEGES ON DATABASE <DB名> TO <PostgreSQLのユーザ名>;

ユーザが作成されたか否かは、次のクエリで確認します。

> SELECT usename FROM pg_user;

この段階では、localhost以外から接続を試みても、まだエラーになります。

$ psql --host=<PostgreSQLのIPアドレス> -d <DB名> -U <PostgreSQLのユーザ名>
psql: error: connection to server at "<PostgreSQLのIPアドレス>", port 5432 failed: Connection refused
	Is the server running on that host and accepting TCP/IP connections?

サーバへの接続設定

localhost以外からの接続をlistenするように設定します。

PostgreSQLを動かすサーバで、以下のコマンドを実行します。

$ sudo su postgres -c psql
> alter system set listen_addresses to '*';
> exit
$ sudo systemctl restart postgresql

設定されたlisten_addressesは、次のクエリで確認します。

> show listen_addresses;

この段階では、localhost以外から接続を試みると、以下のようにエラーが変化します。

$ psql --host=<PostgreSQLのIPアドレス> -d <DB名> -U <PostgreSQLのユーザ名>
psql: error: connection to server at "<PostgreSQLのIPアドレス>", port 5432 failed: FATAL:  no pg_hba.conf entry for host "<接続元のIPアドレス>", user "<PostgreSQLのユーザ名>", database "<DB名>", SSL encryption
connection to server at "<PostgreSQLのIPアドレス>", port 5432 failed: FATAL:  no pg_hba.conf entry for host "<接続元のIPアドレス>", user "<PostgreSQLのユーザ名>", database "<DB名>", no encryption

詳細は以下の参考ページを見てください。

18.3. 接続と認証 | PostgreSQL 9.4.5文書
https://www.postgresql.jp/docs/9.4/runtime-config-connection.html

クライアント認証の設定

最後にクライアント認証の設定です。

PostgreSQLを動かすサーバで、pg_hba.confファイルを編集します。
確認した環境では、/etc/postgresql/14/main/pg_hba.confにありました。

次の行を追加します。

host  all  <PostgreSQLのユーザ名>  <接続元のIPアドレス>  md5

次のコマンドで、再起動します。

$ sudo systemctl restart postgresql

ここまでの設定で、localhost以外から接続できるようになると思います。

$ psql --host=<PostgreSQLのIPアドレス> -d <DB名> -U <PostgreSQLのユーザ名>

詳細は以下の参考ページを見てください。

19.1. pg_hba.confファイル | PostgreSQL 9.4.5文書
https://www.postgresql.jp/docs/9.4/auth-pg-hba-conf.html

※接続を試みた時に出てくるエラーがこのエントリの説明と異なる場合は、ファイヤーウォール等が影響しているかも知れないです。

以上。