Skip to content

Instantly share code, notes, and snippets.

@danielmoralesp
Created June 28, 2021 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielmoralesp/66942100c93789493ced27ed2aaf1f54 to your computer and use it in GitHub Desktop.
Save danielmoralesp/66942100c93789493ced27ed2aaf1f54 to your computer and use it in GitHub Desktop.
Easy way o Dockerize Rails App

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 "$@"

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: postgres
  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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment