Connecting Our Rails App to Postgres

We’ve just seen that our database is up and running and reachable from other containers in our app’s network. However, before we can start making use of it, we have to configure our Rails app to connect to it.

Let’s do this now.

Installing the Postgres Gem

First things first. In order to get our Rails app talking to Postgres, we need to install the Postgres client gem. Open up your Gemfile and update it to replace:

 gem ​'sqlite3'

with:

 gem ​'pg'​, ​'~> 1.0'

To actually install the new gem, we need to run bundle install, which we do by rebuilding our image (we discuss gem management further). Let’s first stop our Rails server:

 $ ​​docker-compose​​ ​​stop​​ ​​web

and then rebuild our image:

 $ ​​

Get Docker for Rails Developers now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.