Part 3: Docker with rails, postgres (database which is running outside the docker)

Praaveen Vr
praaveen
Published in
3 min readFeb 1, 2018

Here we are going see how docker cab be added to the existing rails application.

Files need to be created and updated

a. Dockerfile

b. docker-compose.yml

c. database.yml

Dockerfile

FROM ruby:2.4.0
RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs
RUN mkdir /myapp
WORKDIR /myapp
COPY Gemfile /myapp/Gemfile
COPY Gemfile.lock /myapp/Gemfile.lock
RUN bundle install
COPY . /myapp

docker-compose.yml

version: '3'
services:
db:
image:
postgres
web:
build:
.
command: bundle exec rails s -p 3000 -b '0.0.0.0'
volumes:
- .:/myapp
ports:
- "3000:3000"
depends_on:
- db

Look for docker ip address and replace it with localhost in database.yml

example : host: 172.17.0.1

$ ifconfig

This method we are connecting to the database which is running outside the docker. So data persist.

database.yml

default: &default
adapter: postgresql
encoding: utf8
pool: 5
username: postgres
password: enter_password
host: 172.17.0.1


development:
<<:
*default
database: project_db

test:
<<:
*default
database: project_db

production:
<<:
*default
database: project_db

If find any problem in postgres error authentication failed look here

If your postgres does not allow to connect for the ip address (ex: 172.17.0.1), then do the below listed changes

If your postgres does not allow to connect for the ip address (ex: 172.17.0.1). Then do the below listed changes

Changes to be made at two places (Path : /etc/postgresql/[version]/main/pg_hba.conf)

1.postgresql.conf

2. pg_hba.conf

  1. postgresql.conf

Open the file and look for the line listern_addresses. Set it to ‘*’

For me previously it was commented and looks like

#listern_addresses = 'localhost'

Change to

 listern_addresses = '*'

2. pg_hba.conf

open the file add the host. IP address shown in the docker and additional if required. example: 172.17.0.1 in ifconfig section

host   all     all    172.17.0.0/24    md5 

All set I guess, then from project path run the below listed commands

$ docker-compose build  # Build the application
$ docker-compose up     # Start the application

hit 172.17.0.1:3000

You are done!!

$ docker-compose down   # stop the application

Rails repo can be found at here for reference

back to docker Series

--

--