dbに接続できない - could not connect to server

Dockerを使ってRails6の環境を作り、docker-compose upで起動すると、以下のようなエラーが表示されました。

PG::ConnectionBad: 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"?

原因と解決策

調べてみるとこれは、railsがホストマシーンに接続しようとしていることが原因でした。ということでrailsのconfig/database.ymlを確認すると、username/password/hostを指定し忘れていました。

default: &default
  adapter: postgresql
  encoding: unicode
  # For details on connection pooling, see Rails configuration guide
  # https://guides.rubyonrails.org/configuring.html#database-pooling
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  # username/password/hostを指定してない!


なので、docker-compose.ymlで指定している値をdatabase.ymlに設定してあげます。

version: "3"

services:
  postgres:
      image: postgres
      environment:
        POSTGRES_USER: 'admin'
        POSTGRES_PASSWORD: 'admin-pass'
      restart: always
 ...


image名、POSTGRES_USER, POSTGRES_PASSWORDの値を、database.ymlにも指定します。

default: &default
  adapter: postgresql
  encoding: unicode
  # For details on connection pooling, see Rails configuration guide
  # https://guides.rubyonrails.org/configuring.html#database-pooling
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  username: admin
  password: admin
  host: postgres


これで無事アクセスに成功しました。