Back-end Engineering Articles

I write and talk about backend stuff like Ruby, Ruby On Rails, Databases, Testing, Architecture / Infrastructure / System Design, Cloud, DevOps, Backgroud Jobs, and more...

Twitter:
@daniel_moralesp

2020-02-07

Easy Way To Dockerize Rails App

Original link: https://gist.github.com/danielmoralesp/66942100c93789493ced27ed2aaf1f54

Following this tutotial https://docs.docker.com/samples/rails/

$ mkdir myapp
$ touch Dockerfile

# syntax=docker/dockerfile:1
FROM ruby:2.7.1
RUN apt-get update -qq && apt-get install -y nodejs postgresql-client
WORKDIR /myapp
COPY Gemfile /myapp/Gemfile
COPY Gemfile.lock /myapp/Gemfile.lock
RUN bundle install

# Add a script to be executed every time the container starts.
COPY entrypoint.sh /usr/bin/
RUN chmod +x /usr/bin/entrypoint.sh
ENTRYPOINT ["entrypoint.sh"]
EXPOSE 3000

# Configure the main process to run when running the image
CMD ["rails", "server", "-b", "0.0.0.0"]

Create Gemfile

$ touch Gemfile

source '<https://rubygems.org>'
gem 'rails', '~> 6.0.4'

$ touch Gemfile.lock ## leave blank
$ touch entrypoint.sh

#!/bin/bash
set -e

# Remove a potentially pre-existing server.pid for Rails.
rm -f /myapp/tmp/pids/server.pid

# Then exec the container's main process (what's set as CMD in the Dockerfile).
exec "[email protected]"

Create docker-compuse file

$ touch docker-compose.yml

version: "3"
services:
  db:
    image: postgres
    volumes:
      - ./tmp/db:/var/lib/postgresql/data
    environment:
      POSTGRES_PASSWORD: password
  web:
    build: .
    command: bash -c "rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'"
    volumes:
      - .:/myapp
    ports:
      - "3000:3000"
    depends_on:
      - db

Build project

$ sudo docker-compose run --no-deps web rails new . --force --database=postgresql
$ sudo chown -R $USER:$USER .
$ sudo docker-compose build

Connect the database

# Open config/database.yml

default: &default
  adapter: postgresql
  encoding: unicode
  host: db
  username: username
  password: password
  pool: 5

development:
  <<: *default
  database: myapp_development

test:
  <<: *default
  database: myapp_test
In console

$ sudo docker-compose up
Finally, you need to create the database. In another terminal, run:

$ sudo docker-compose run web rake db:create
View the Rails welcome page! (http://localhost:3000)

Other important commands

$ sudo docker-compose run web rake db:migrate
$ sudo docker-compose run web rails g scaffold Idea title body
$ sudo docker-compose run web rails g Model Idea title body:text
$ sudo docker-compose run web rails c
$ sudo docker-compose run web bundle install
$ sudo docker-compose up --build
$ sudo docker-compose down
$ sudo docker-compose up