[Ruby] Procedure to build Rails application development environment with Docker [Rails, MySQL, Docker]

1 minute read

Hello. This time, I summarized the procedure to build the development environment of Rails application with Docker. I am still short of studying, so if you have any corrections or improvements, I would appreciate it if you could point me out.

Advance preparation

environment

Ruby: 2.5.8 Rails: 5.2.4.3 MySQL: 5.7.31 Docker: 19.03.8 Docker Compose: 1.25.4

procedure

1. Create project root directory

terminal



$ mkdir test-app

First, create the project root directory.

2. Add files directly under the root directory

terminal



$ cd test-app
$ touch Dockerfile docker-compose.yml Gemfile Gemfile.lock

Create four files, Dockerfile, docker-compose.yml, Gemfile, and Gemfile.lock, directly under the created root directory. The contents of each file are as follows (leave Gemfile.lock empty):

Dockerfile



FROM ruby:2.5
RUN apt-get update && apt-get install -y \
    build-essential \
    nodejs
WORKDIR /test-app
COPY Gemfile Gemfile.lock /test-app/
RUN bundle install

docker-compose.yml



version: '3'

volumes:
  mysql-data:

services:
  web:
    build:.
    command: bundle exec rails s -p 3000 -b '0.0.0.0'
    ports:
      -'3000:3000'
    volumes:
      -'.:/test-app'
    tty: true
    stdin_open: true
    depends_on:
      -db
    links:
      -db

  db:
    image: mysql:5.7
    volumes:
      -'mysql-data:/var/lib/mysql'
    environment:
      -'MYSQL_ROOT_PASSWORD=test-app'

Gemfile



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

3. Set up Rails in the container

terminal


$ docker-compose run --rm web rails new .--force --database=mysql --skip-bundle --skip-test

Run rails new in the web container. Since I was planning to use RSpec for testing this time, I also added --skip-test.

4. Edit the created config/database.yml

Edit the config/database.yml created by Rails setup as follows.

config/database.yml



default: &default
  adapter: mysql2
  encoding: utf8
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") {5} %>
  username: root
  password: set the value of MYSQL_ROOT_PASSWORD of test-app #docker-compose.yml
  host: db Match with service name in #docker-compose.yml

development:
  <<: *default
  database: test-app_development

5. Start the container

terminal



$ docker-compose up --build -d
$ docker-compose run --rm web rails db:create

Now when you access http://localhost:3000, you should see the Rails home screen.

rails_home_pic.png

reference