LoginSignup
73
80

More than 5 years have passed since last update.

Docker入門 #5 【Ruby on Rails5環境構築】

Last updated at Posted at 2017-10-11

2_.png

今回は公式のQuickstart: Compose and Railsを改良したものです

完成品
https://github.com/wMETAw/rails5-on-docker

構成

service version
Ruby 2.3.3
Rails 5.0.0.1
Mysql 5.7

enter image description here

Dockerfile

Dockerfile
FROM ruby:2.3.3

# RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs
RUN apt-get update -qq
RUN apt-get install -y build-essential 
RUN apt-get install -y libpq-dev
RUN apt-get install -y nodejs

# ワーキングディレクトリの設定
RUN mkdir /myapp
WORKDIR /myapp

# gemfileを追加する
ADD Gemfile /myapp/Gemfile
ADD Gemfile.lock /myapp/Gemfile.lock

# gemfileのinstall
RUN bundle install
ADD . /myapp

RUN apt-get ...はタイムアウトやエラーが発生する場合があるので縦並びに記述した方が良いと思います!
見やすいですし!

Gemfile , Gemfile.lock

Gemfile
source 'https://rubygems.org'
gem 'rails', '5.0.0.1'
terminal
# 空の.lockファイルを作成
$ touch Gemfile.lock

docker-compose.yml

docker-compose.yml
db:
  image: mysql:5.7
  environment:
    MYSQL_ROOT_PASSWORD: root

web:
  build: .
  command: bundle exec rails s -p 3000 -b '0.0.0.0'
  volumes:
    - .:/myapp
  ports:
    - "3000:3000"
  links:
    - db

rails newでプロジェクトを作成

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

DBhostの修正

config/database.yml
default: &default
  adapter: mysql2
  encoding: utf8
  pool: 5
  username: root
  password: root # docker-compose.ymlのMYSQL_ROOT_PASSWORD 
  host: db       # docker-compose.ymlのサービス名

起動

terminnal
# コンテナをビルド
$ docker-compose build

# コンテナの一斉起動
$ docker-compose up

DB作成

terminnal
$ docker-compose run web rails db:create

確認

2_.png

FOO↑↑

scaffoldでCRUDを生成してみる

terminnal
# scaffold
$ docker-compose run web rails g scaffold users name:string

# migration
$ docker-compose run web rails db:migrate

3_.png

さいごに

Rails場合、OSとgemとrubyのバージョンの依存関係でごちゃごちゃになり、各々のマシンだとインストールエラーが必ずと言っていいほど発生します
(v8・rubyracer・nokogiriなど)

環境を統一できるDockerはRailsに向いてるなーって思いました。

また、 Rails 5.1対応第4版Railsチュートリアルが2017年8月に公開されました!

本当にありがたいですね!

今回で入門記事は終わりです
お疲れ様でした!

リンク

Docker入門 #1 【Dockerとは】
Docker入門 #2 【Dockerチュートリアル】
Docker入門 #3 【WordPress環境構築】
Docker入門 #4 【CodeIgniter環境構築】
Docker入門 #5 【Ruby on Rails5環境構築】
Docker コマンドチートシート

73
80
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
73
80