shou2017.com
JP

Creating a Rails Environment with Docker

Mon Sep 3, 2018
Sat Aug 10, 2024

Creating a Rails environment with Docker. This is purely a memo for myself.

Setup

Docker Community Edition for Mac

Install the stable version.

Create a Docker Hub account

That’s all.

Docker Compose

Check if Docker Compose is installed. It comes by default with Docker Community Edition for Mac.

$ docker-compose -v
docker-compose version 1.22.0, build f46880f

Docker Compose is commonly used in development environments and automated testing. It handles various tasks together.

  • Prepare Dockerfile or Docker Hub
  • Define docker-compose.yml
  • Run docker-compose up (use -d for detached mode)

Creating a Rails Environment

Create a working directory

$ mkdir rails
$ cd rails

Create a Dockerfile

Building an image for the Rails execution environment.

FROM ruby:2.5
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

Create a Gemfile

source 'https://rubygems.org'
gem 'rails', '5.2.0'

Create an empty Gemfile.lock

Create docker-compose.yml

Using postgresql as the database.

Port is 3000.

Use volumes for data persistence. Without this, data will be lost every time the server is restarted.

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

At this point, your setup should look something like this:

Creating a Rails Environment with Docker

Create a Rails project

Use docker-compose to create a Rails project.

For creating in the current directory, use rails new .

--force will overwrite existing files.

rails$ docker-compose run web rails new . --force --database=postgresql

Once rails new is complete, you’ll see the familiar structure.

Creating a Rails Environment with Docker

A warning appears if postgresql is 0.18, so modify it:

Gemfile

gem 'pg', '>= 0.20', '< 2.0'

After updating gems, use docker-compose build instead of bundle install

rails$ docker-compose build

Add database configuration

Update config/database.yml as follows:

<!-- config/database.yml -->

default: &default
  adapter: postgresql
  encoding: unicode
  host: db
  username: postgres
  password:

Launch

Start in detached mode

rails$ docker-compose up -d

Create the database

rails$ docker-compose run web rails db:create

And it’s complete.

Access localhost:3000

Creating a Rails Environment with Docker

If you want to stop currently running containers:

rails$ docker-compose stop

プログラマのためのDocker教科書 第2版

See Also