Build Rails application

Below are steps to build a simple Rails application with PostgreSQL database. If you don't know where to start, or want to have a quick overview, this guide is made for you. Now let's start.


Make sure Docker and Docker Compose are installed on your local PC.

Download Docker here: https://www.docker.com/

Download Docker Compose here: https://docs.docker.com/compose/

Git clone the Rails source, or create a new Rails project.

In this example, I had a Rails project in folder myapp. Now go to the project folder, create a file name Dockerfile like this (you could change the ruby version)

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

The above code will copy code, Gemfile and Gemfile.lock from myapp, then run bundle install to install all the required Gem.

If you're working on exists project, remember to deleted tmp files in bin, to reduce the size of container image.

Now pull PostgreSql

$ docker pull postgres:9.4

From the same directory of Dockerfile, create docker-compose.yml like this

version: '2'
services:
db:
image: postgres:9.4
environment:
POSTGRES_USER: pguser
POSTGRES_PASSWORD: password
POSTGRES_DB: myapp
web:
build: .
command: bundle exec rails s -p 3000 -b '0.0.0.0'
volumes:
- .:/myapp
ports:
- "3000:3000"
links:
- db

Inside config/database.yml, will be similar to this

default: &default
adapter: postgres
encoding: utf8
pool: 5
username: pguser
password: password
host: db

development:
<<: *default
database: myapp

Check if the port is conflicted or not with command: netstat -ntlp

Now simply using 3 commands to run project:
docker-compose build (compile)
docker-compose up (compile if updated, and run)
docker-compose down (remove the image)

In case of first time running, we usually want to run db migrate, then use this command: docker-compose exec web bundle exec rake db:migrate

Thank you for reading. Hope it could help.