[RUBY] Rails Docker environment construction

Premise

A memorandum when building a Docker environment with rails. Docker for mac installed

Main subject

rails
|--Dockerfile
|--Gemfile
|--Gemfile.lock
|--docker-compose.yml

Dockerfile.


FROM ruby:2.4.5
RUN apt-get update -qq && apt-get install -y build-essential nodejs
RUN mkdir /app
WORKDIR /app
COPY Gemfile /app/Gemfile
COPY Gemfile.lock /app/Gemfile.lock
RUN bundle install
COPY . /app

Build a Dockerfile and Docker Image (a template for a container virtual environment is created)

Gemfile.


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

Gemfile (define the gem you want to install) → execute bundle install command → gem is installed → installed gem is described in Gemfile.lock

docker-compose.yml


version: '3'
services:
  web:    #Rails container definition
    build:  .  #Creating and using an image based on the Dockerfile
    command: bundle exec rails s -p 3000 -b '0.0.0.0'  #Rails start command
    volumes:
      - .:/app
    ports:
      - 3000:3000  #<Port number to publish>:<Transfer destination port number inside the container>
    depends_on:
      - db  #Set the MySQL server to start first before Rails starts
    tty: true
    stdin_open: true
  db:    #MySQL server container definition
    image: mysql:5.7
    volumes:
      - db-volume:/var/lib/mysql
    environment:
      MYSQL_ROOT_PASSWORD: password
volumes:
  db-volume:  #By this definition db on PC-A volume (data holding area) is created with the name volume

After completing the above settings, create a Rails project in the terminal

terminal.


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

docker-compose run web </ code> is a command to execute the following command in the web service container

--force </ code> is an option to overwrite existing files -databace = mysql </ code> is an option to put settings to use MySQL

After the build is complete, edit the database file used by Rails

config/database.yml


#abridgement

default: &default
  adapter: mysql2
  encoding: utf8
  pool: 5
  username: root
  password: password  #Edit
  host: db  #Edit

#abridgement

After completing the settings, enter the following command in the terminal

terminal.


rails$ docker-compose up -d

The above is the command to start the container (virtual environment) based on docker-compose.yml in the current directory

Next, since the database for the development environment has not been created, create it with the following command

terminal.


rails$ docker-compose run web bundle exec rake db:create

The bundle exec rake </ code> part executes the rake command installed in the Rails environment. rake db: create </ code> creates a database for Rails on the MySQL server

Enter localhost: 3000 in your browser and when the Rails screen appears, you're done!

Recommended Posts