書きたいこと:
Dockerを使用してWebアプリを作る過程で発生したActiveRecord::ConnectionNotEstablished
エラーをどうやって解消したか、記録に残しておく。
発生したエラー:
connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory
Is the server running locally and accepting connections on that socket?
Couldn't create 'app_development' database. Please check your configuration.
bin/rails aborted!
ActiveRecord::ConnectionNotEstablished: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory (ActiveRecord::ConnectionNotEstablished)
Is the server running locally and accepting connections on that socket?
Caused by:
PG::ConnectionBad: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory (PG::ConnectionBad)
Is the server running locally and accepting connections on that socket?
Tasks: TOP => db:create
エラーの原因:
Docker 内で PostgreSQL に接続しようとするとき、TCP 接続 (host: db) を使う必要があるが、設定ミスでUNIX ドメインソケット (/var/run/postgresql/.s.PGSQL.5432) を使おうとしていた
解決法:
①設定ファイルに下記の内容を追加して、TCP接続を行うように設定
config\database.yml
development:
<<: *default
database: app_development
host: dbname # コメントアウトを解除し、localhostではなくデータベースサーバーのホスト名(コンテナ名)を設定
docker-compose.yml
services:
environment:
DATABASE_URL: postgres://username:password@severname:5432/dbname # 設定値はサンプル
②Docker compose up
を実行
結果:
http://localhost:3000/
でログインできた!