Home > Enterprise >  how to connect Rails app to docker postgres on host machine
how to connect Rails app to docker postgres on host machine

Time:11-11

I want to run a postgres container like so, without docker compose, and connect to it in a Ruby on Rails app:

docker run -p 5432:5432 -e POSTGRES_USER=user -e POSTGRES_PASSWORD=password -e POSTGRES_DB=myapp_development postgres:13.4

my database.yml file looks like this

default: &default
  adapter: postgresql
  encoding: unicode
  # For details on connection pooling, see rails configuration guide
  # http://guides.rubyonrails.org/configuring.html#database-pooling
  pool: 5

development:
  <<: *default
  database: myapp_development
  user: user
  password: password

However, when running the app I get the following error:

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

I don't want to use docker compose currently

What am I missing?

CodePudding user response:

After run

docker run -p 5432:5432 -e POSTGRES_USER=user -e POSTGRES_PASSWORD=password -e POSTGRES_DB=myapp_development postgres:13.4

I'm able to connect postgresql from my terminal by running

psql -h localhost  -U user myapp_development

So, I guess you just need to add host option to database.yml

default: &default
  adapter: postgresql
  encoding: unicode
  # For details on connection pooling, see rails configuration guide
  # http://guides.rubyonrails.org/configuring.html#database-pooling
  pool: 5
  host: localhost

development:
  <<: *default
  database: myapp_development
  user: user
  password: password

  • Related