PostgreSQL に「Connection refused」で接続できない(port 5432)
「Is the server running on host ... and accepting TCP/IP connections on port 5432?」は、サーバー未起動・listen_addresses 未設定・ポート/公開ミスのいずれか。
起動状態と待ち受け設定を順に確認する。
#postgresql#connection-refused#listen_addresses#port#5432
公開:
要約
could not connect to server: Connection refused と Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? は、その host:port に待ち受けているプロセスが無いという意味。
認証より手前の段階で弾かれている。
サーバーが起動しているか、listen_addresses が対象 IP を含むか、ポートが合っているかを順に潰す。
よくある原因
- サーバー未起動: インストール直後や再起動後で、サービスが上がっていない。
- listen_addresses の制限: 既定は
localhostのため、別ホストや別インターフェイスからは待ち受けていない。 - ポート違い: 既定 5432 だが、複数バージョン同居や設定変更で別ポートになっている。
- Docker のポート未公開: コンテナ内では動いていても、
-p 5432:5432が無いとホストから届かない。
よくある原因の切り分け
まず本当に起動しているか、どのポートで待っているかを確認する。
# Linux: 待ち受けポートとプロセスを確認
ss -ltnp | grep 5432
# サービス状態(systemd の例)
systemctl status postgresql解決策
1. サーバーを起動する
環境ごとに起動方法が異なる。
# systemd
sudo systemctl start postgresql
# Homebrew (macOS)
brew services start postgresql@162. listen_addresses と port を設定して再起動する
外部や別インターフェイスから繋ぐ場合は postgresql.conf を変更する。
listen_addresses = '*'
port = 5432listen_addresses の変更は reload では反映されず再起動が必要(Connections and Authentication)。
あわせて pg_hba.conf で接続元を許可する。
3. Docker ならポートを publish する
docker run -e POSTGRES_PASSWORD=secret -p 5432:5432 postgres:16ホスト側からは localhost:5432 で届くようになる。
コンテナ間なら相手はサービス名で解決する。