Build and run your first Ruby On Rails Docker

Build and run your first Ruby On Rails Docker

2019, Sep 22    

In the recent year, the Ruby On Rails deployment has been shift from tranditional linux server to dockerization. Even myself has stop deploy Rails to production with linux server anymore. So in this blog I would like to help some starter to dockerize their Rails app with these simple step below.


Create your ROR app

rails new SampleRailsDocker --database=postgresql

Your config/database.yml should look like

default: &default
  adapter: postgresql
  encoding: unicode
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  <<: *default
  database: dev_db_name
  <<: *default
  database: <%= ENV['DATABASE_NAME'] %>
  username: <%= ENV['DATABASE_USER'] %>
  password: <%= ENV['DATABASE_PASSWORD'] %>
  password: <%= ENV['DATABASE_HOST'] %>

We will use Ruby alpine to create our docker image. So Dockerfile should look like

FROM ruby:2.5.3-alpine
RUN apk add --no-cache --update build-base \
                                linux-headers \
                                git \
                                postgresql-dev \
                                nodejs \
RUN mkdir /myapp
WORKDIR /myapp
COPY Gemfile /myapp/Gemfile
COPY Gemfile.lock /myapp/Gemfile.lock
RUN bundle install
COPY . /myapp

We use docker compose to help run our docker image. In docker-compose.yml we have two services. One is database (postgres) and web is our Rails app.

version: '3'
    image: postgres:11.1-alpine
      - POSTGRES_PASSWORD=password
      - POSTGRES_USER=db_user
      - POSTGRES_DB=rails_dev
    build: .
    image: uysimty/rails-sample
    command: bin/rails s -p 3000 -b ''
      - DATABASE_PASSWORD=password
      - DATABASE_USER=db_user
      - DATABASE_NAME=rails_dev
      - DATABASE_HOST=db
      - "3000:3000"
      - db

Build docker image run command

docker-compose build

Push docker image to cloud

docker-compose push web

Run migration

docker-compose run --rm web rails db:migrate

Our fresh new rails app didn’t have any migration yet but this is useful if we have the migration pending

Run locally

docker-compose up

Now on browser go to http://localhost:3000 you will see your Ruby On Rails welcome page.

Related Post

Set Timezone by each user

Small gist snippet for working with timezone base on user, team, group, company, tenency, etc......

1 minute read