[RUBY] Rails Docker environment construction


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

Main subject



FROM ruby:2.4.5
RUN apt-get update -qq && apt-get install -y build-essential nodejs
RUN mkdir /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)


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

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


version: '3'
  web:    #Rails container definition
    build:  .  #Creating and using an image based on the Dockerfile
    command: bundle exec rails s -p 3000 -b ''  #Rails start command
      - .:/app
      - 3000:3000  #<Port number to publish>:<Transfer destination port number inside the container>
      - 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
      - db-volume:/var/lib/mysql
      MYSQL_ROOT_PASSWORD: password
  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


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



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


After completing the settings, enter the following command in the 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


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