LoginSignup
293
282

More than 5 years have passed since last update.

Vagrant で Ruby on Rails の環境を構築するまでの手順

Last updated at Posted at 2014-06-29

rails-dev-box を使うと以下の手順よりも簡単に環境構築出来るかもしれません (手順はこちらをご参考)。
以下の手順で作る環境と rails-dev-box で出来上がる環境は色々違うので自分にあったものを選ぶといいと思います。


この手順でつくる環境

種類 バージョン
CentOS 7.0-x86_64
rbenv rbenv 0.4.0-98-g13a474c
Ruby 2.1.3
Rails 4.1.6

1. 仮想マシン作成

  1. VirtualBoxインストール

  2. Vagrantインストール

  3. CentOS のBoxを取得

    Boxを配布している Vagrantbox.es からCentOSのBoxを適当に選んで追加。

    terminal
    $ vagrant box add CentOS7 https://dl.dropboxusercontent.com/s/w3lbekm7eunrskm/centos-7.0-x86_64.box
    
    実行結果
    ==> box: Adding box 'CentOS7' (v0) for provider: 
        box: Downloading: https://dl.dropboxusercontent.com/s/w3lbekm7eunrskm/centos-7.0-   x86_64.box
    ==> box: Successfully added box 'CentOS7' (v0) for 'virtualbox'!
    
  4. 仮想マシンを作成

    terminal
    $ vagrant init CentOS7
    
    実行結果
    A `Vagrantfile` has been placed in this directory. You are now
    ready to `vagrant up` your first virtual environment! Please read
    the comments in the Vagrantfile as well as documentation on
    `vagrantup.com` for more information on using Vagrant.
    
  5. Vagrantfileを編集

    terminal
    $ vi Vagrantfile 
    

    27行目の # config.vm.network "private_network", ip: "192.168.33.10" をコメントを外す。

    Vagrantfile
    # -*- mode: ruby -*-
    # vi: set ft=ruby :
    
    # Vagrantfile API/syntax version. Don't touch unless you know what you're doing!
    VAGRANTFILE_API_VERSION = "2"
    
    Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
      # All Vagrant configuration is done here. The most common configuration
      # options are documented and commented below. For a complete reference,
      # please see the online documentation at vagrantup.com.
    
      # Every Vagrant virtual environment requires a box to build off of.
      config.vm.box = "CentOS7"
    
      # Disable automatic box update checking. If you disable this, then
      # boxes will only be checked for updates when the user runs
      # `vagrant box outdated`. This is not recommended.
      # config.vm.box_check_update = false
    
      # Create a forwarded port mapping which allows access to a specific port
      # within the machine from a port on the host machine. In the example below,
      # accessing "localhost:8080" will access port 80 on the guest machine.
      # config.vm.network "forwarded_port", guest: 80, host: 8080
    
      # Create a private network, which allows host-only access to the machine
      # using a specific IP.
      config.vm.network "private_network", ip: "192.168.33.10"
    
      # Create a public network, which generally matched to bridged network.
      # Bridged networks make the machine appear as another physical device on
      # your network.
      # config.vm.network "public_network"
    .
    .
    .
    
  6. 仮想マシンを起動

    terminal
    $ vagrant up
    
    実行結果
    Bringing machine 'default' up with 'virtualbox' provider...
    ==> default: Importing base box 'CentOS7'...
    ==> default: Matching MAC address for NAT networking...
    ==> default: Setting the name of the VM: sandbox_default_1411431118266_81879
    ==> default: Fixed port collision for 22 => 2222. Now on port 2200.
    ==> default: Clearing any previously set network interfaces...
    ==> default: Preparing network interfaces based on configuration...
        default: Adapter 1: nat
        default: Adapter 2: hostonly
    ==> default: Forwarding ports...
        default: 22 => 2200 (adapter 1)
    ==> default: Booting VM...
    ==> default: Waiting for machine to boot. This may take a few minutes...
        default: SSH address: 127.0.0.1:2200
        default: SSH username: vagrant
        default: SSH auth method: private key
        default: Warning: Connection timeout. Retrying...
    ==> default: Machine booted and ready!
    ==> default: Checking for guest additions in VM...
    ==> default: Configuring and enabling network interfaces...
    ==> default: Mounting shared folders...
        default: /vagrant => /Users/yamagh/GoogleDrive/Local/dev/ruby/sandbox
    
  7. 仮想マシンにSSHでログイン

    terminal
    $ vagrant ssh
    
    実行結果
    Last login: Wed Aug 20 14:47:28 2014
    [vagrant@vagrant-centos7 ~]$ 
    

2. 準備

  1. CentOSに入ってるRubyはバージョンが古いのでアンインストール

    terminal
    $ sudo yum -y remove ruby
    
    実行結果
    [root@vagrant-centos7 vagrant]# yum -y remove ruby
    読み込んだプラグイン:fastestmirror
    Repodata is over 2 weeks old. Install yum-cron? Or run: yum makecache fast
    依存性の解決をしています
    --> トランザクションの確認を実行しています。
    ---> パッケージ ruby.x86_64 0:2.0.0.353-20.el7 を 削除
    .
    .
    .
    省略
    .
    .
    .
      rubygem-bigdecimal.x86_64 0:1.2.0-20.el7         rubygem-io-console.x86_64 0:0.4.2-20.el7        
      rubygem-json.x86_64 0:1.7.7-20.el7               rubygem-psych.x86_64 0:2.0.0-20.el7             
      rubygem-rdoc.noarch 0:4.0.0-20.el7               rubygems.noarch 0:2.0.14-20.el7                 
    
    完了しました!
    
  2. gitをインストール

    terminal
    $ sudo yum -y install git
    
    実行結果
    [root@vagrant-centos7 vagrant]# yum -y install git
    読み込んだプラグイン:fastestmirror
    Repodata is over 2 weeks old. Install yum-cron? Or run: yum makecache fast
    base                                                                        | 3.6 kB  00:00:00     
    extras                                                                      | 3.4 kB  00:00:00     
    puppetlabs-deps                                                             | 2.5 kB  00:00:00     
    .
    .
    .
    省略
    .
    .
    .
    依存性関連をインストールしました:
      libgnome-keyring.x86_64 0:3.8.0-3.el7            perl-Error.noarch 1:0.17020-2.el7               
      perl-Git.noarch 0:1.8.3.1-4.el7                  perl-TermReadKey.x86_64 0:2.30-20.el7           
      rsync.x86_64 0:3.0.9-15.el7                     
    
    完了しました!
    
  3. 開発環境では不要なのでファイアウォールを停止

  • CentOS7の場合

    terminal
    $ sudo systemctl stop firewalld
    $ sudo systemctl mask firewalld
    
  • CentOS6以前の場合

    terminal
    $ sudo service iptables stop
    $ sudo chkconfig iptables off
    

3. rbenvインストール

3-1. 特定のユーザー用にインストールする場合

  1. rbenvリポジトリをclone

    terminal
    $ git clone https://github.com/sstephenson/rbenv.git ~/.rbenv
    
    実行結果
    Cloning into '/home/vagrant/.rbenv'...
    remote: Counting objects: 1889, done.
    remote: Total 1889 (delta 0), reused 0 (delta 0)
    Receiving objects: 100% (1889/1889), 298.61 KiB | 197.00 KiB/s, done.
    Resolving deltas: 100% (1178/1178), done.
    
  2. PATHを通す

    terminal
    $ echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bash_profile
    
  3. ターミナル(bash)実行時に rbenv init を実行するように設定

    terminal
    $ echo 'eval "$(rbenv init -)"' >> ~/.bash_profile
    
  4. 確認

    terminal
    $ cat ~/.bash_profile
    
    実行結果
    # .bash_profile
    
    # Get the aliases and functions
    if [ -f ~/.bashrc ]; then
        . ~/.bashrc
    fi
    
    # User specific environment and startup programs
    
    PATH=$PATH:$HOME/.local/bin:$HOME/bin
    
    export PATH
    export PATH="$HOME/.rbenv/bin:$PATH"
    eval "$(rbenv init -)"
    

    手順2と3でechoした内容が末尾2行に追加されていることを確認する。

  5. .bash_profile のリロード

    terminal
    $ source ~/.bash_profile
    
  6. インストール確認

    terminal
    $ rbenv --version
    
    実行結果
    rbenv 0.4.0-98-g13a474c
    
  7. ruby-buildをインストール

    terminal
    $ git clone https://github.com/sstephenson/ruby-build.git ~/.rbenv/plugins/ruby-build
    
    実行結果
    Cloning into '/home/vagrant/.rbenv/plugins/ruby-build'...
    remote: Counting objects: 3786, done.
    remote: Compressing objects: 100% (31/31), done.
    remote: Total 3786 (delta 16), reused 2 (delta 0)
    Receiving objects: 100% (3786/3786), 661.69 KiB | 361.00 KiB/s, done.
    Resolving deltas: 100% (1859/1859), done.
    

3-2. 全ユーザー用にインストールする場合

  1. rbenvリポジトリをclone

    terminal
    $ git clone git://github.com/sstephenson/rbenv.git /usr/local/
    
  2. PATHを通す

    terminal
    $ echo 'export RBENV_ROOT="/usr/local/rbenv"' >> /etc/profile
    $ echo 'export PATH="${RBENV_ROOT}/bin:${PATH}"' >> /etc/profile
    $ echo 'eval "$(rbenv init -)"' >> /etc/profile
    
  3. ruby-buildプラグインをインストール

    terminal
    $ mkdir /usr/local/rbenv/plugins
    $ git clone git://github.com/sstephenson/ruby-build.git /usr/local/rbenv/plugins
    

4. Rubyのインストール

  1. Rubyの最新バージョンを確認

    terminal
    $ rbenv install -l
    
    実行結果
    Available versions:
      1.8.6-p383
      1.8.6-p383
      1.8.6-p420
    .
    .
    .
    省略
    .
    .
    .
      2.1.3
      2.2.0-dev
      2.2.0-dev
      2.2.0-preview1
      2.2.0-preview1
      jruby-1.5.6
      jruby-1.5.6
    

    rubyのバージョン一覧がずらずらと表示されるので、中から最新のバージョンを確認。上の実行結果の場合だと2.1.3が最新の安定バージョン。

  2. Rubyのインストール

    terminal
    $ rbenv install 2.1.3
    
    実行結果
    Downloading ruby-2.1.3.tar.gz...
    -> http://dqw8nmjcqpjn7.cloudfront.net/ 0818beb7b10ce9a058cd21d85cfe1dcd233e98b7342d32e9a5d4bebe98347f01
    Installing ruby-2.1.3...
    Installed ruby-2.1.3 to /home/vagrant/.rbenv/versions/2.1.3
    

    ここで以下の様なエラーが表示される場合は、OpenSSLのライブラリが必要なためインストールする。

    エラー:The_Ruby_openssl_extension_was_not_compiled._Missing_the_OpenSSL_lib?
    [vagrant@vagrant-centos7 ~]$ rbenv install 2.1.3
    Downloading ruby-2.1.3.tar.gz...
    -> http://dqw8nmjcqpjn7.cloudfront.net/0818beb7b10ce9a058cd21d85cfe1dcd233e98b7342d32e9a5d4bebe98347f01
    Installing ruby-2.1.3...
    
    BUILD FAILED (CentOS Linux 7 using ruby-build 20140919-2-g04fe8ab)
    
    Inspect or clean up the working tree at /tmp/ruby-build.20140923014200.3430
    Results logged to /tmp/ruby-build.20140923014200.3430.log
    
    Last 10 log lines:
                                  rake 10.1.0
                                  rdoc 4.1.0
                                  test-unit 2.1.3.0
    installing rdoc:              /home/vagrant/.rbenv/versions/2.1.3/share/ri/2.1.0/system
    installing capi-docs:         /home/vagrant/.rbenv/versions/2.1.3/share/doc/ruby
    The Ruby openssl extension was not compiled. Missing the OpenSSL lib?
    Configure options used:
      --prefix=/home/vagrant/.rbenv/versions/2.1.3
      LDFLAGS=-L/home/vagrant/.rbenv/versions/2.1.3/lib 
      CPPFLAGS=-I/home/vagrant/.rbenv/versions/2.1.3/include 
    
    terminal
    $ sudo yum -y install openssl-devel
    
    実行結果
    .
    .
    .
    インストール:
      openssl-devel.x86_64 1:1.0.1e-34.el7_0.4                                                         
    
    依存性関連をインストールしました:
      keyutils-libs-devel.x86_64 0:1.5.8-3.el7          krb5-devel.x86_64 0:1.11.3-49.el7             
      libcom_err-devel.x86_64 0:1.42.9-4.el7            libselinux-devel.x86_64 0:2.2.2-6.el7         
      libsepol-devel.x86_64 0:2.1.9-3.el7               libverto-devel.x86_64 0:0.2.5-4.el7           
      pcre-devel.x86_64 0:8.32-12.el7                   zlib-devel.x86_64 0:1.2.7-13.el7              
    
    完了しました!
    

     

    次のようなエラーが表示される場合、こちらの記事の手順で対処する。
    原因はRubyのOpenSSL Extensionに関する既知の問題Ruby 2.0.0-p247 以下のバージョンを Fedora/RedHat にインストールしようとすると発生するとのこと。

    [vagrant@vagrant-centos7 ~]$ rbenv install 2.0.0-p0
    Downloading yaml-0.1.6.tar.gz...
    -> http://dqw8nmjcqpjn7.cloudfront.net/7da6971b4bd08a986dd2a61353bc422362bd0edcc67d7ebaac68c95f74182749
    Installing yaml-0.1.6...
    Installed yaml-0.1.6 to /home/vagrant/.rbenv/versions/2.0.0-p0
    
    Downloading ruby-2.0.0-p0.tar.gz...
    -> http://dqw8nmjcqpjn7.cloudfront.net/aff85ba5ceb70303cb7fb616f5db8b95ec47a8820116198d1c866cc4fff151ed
    Installing ruby-2.0.0-p0...
    
    BUILD FAILED (CentOS Linux 7 using ruby-build 20141113-8-g63f6fa2)
    
    Inspect or clean up the working tree at /tmp/ruby-build.20141124022257.6330
    Results logged to /tmp/ruby-build.20141124022257.6330.log
    
    Last 10 log lines:
                            ^
    ossl_pkey_ec.c:821:29: エラー: ‘EC_GROUP_new_curve_GF2m’ が宣言されていません (この関数内での最初の使用)
                     new_curve = EC_GROUP_new_curve_GF2m;
                                 ^
    ossl_pkey_ec.c:821:29: 備考: 未宣言の識別子は出現した各関数内で一回のみ報告されます
    make[2]: *** [ossl_pkey_ec.o] エラー 1
    make[2]: ディレクトリ `/tmp/ruby-build.20141124022257.6330/ruby-2.0.0-p0/ext/openssl' から出ます
    make[1]: *** [ext/openssl/all] エラー 2
    make[1]: ディレクトリ `/tmp/ruby-build.20141124022257.6330/ruby-2.0.0-p0' から出ます
    make: *** [build-ext] エラー 2
    
  3. デフォルトで使用するRubyのバージョンを設定

    terminal
    $ rbenv global 2.1.3
    
  4. インストール結果を確認

    terminal
    $ ruby -v
    
    実行結果
    ruby 2.1.3p242 (2014-09-19 revision 47630) [x86_64-linux]
    

5. Railsのインストール

  1. multi_jsonのインストール

    terminal
    $ gem install multi_json -v '1.10.1'
    
    実行結果
    Fetching: multi_json-1.10.1.gem (100%)
    Successfully installed multi_json-1.10.1
    Parsing documentation for multi_json-1.10.1
    Installing ri documentation for multi_json-1.10.1
    Done installing documentation for multi_json after 0 seconds
    1 gem installed
    

    これを入れずに手順2のBundlerをインストールすると次のエラーになったのでインストール。

    エラー
    An error occurred while installing multi_json (1.10.1), and Bundler cannot continue.
    Make sure that `gem install multi_json -v '1.10.1'` succeeds before bundling.
    
  2. Bundlerのインストール

    terminal
    $ rbenv exec gem install bundler
    
    実行結果
    Fetching: bundler-1.7.3.gem (100%)
    Successfully installed bundler-1.7.3
    Parsing documentation for bundler-1.7.3
    Installing ri documentation for bundler-1.7.3
    Done installing documentation for bundler after 2 seconds
    1 gem installed
    
    terminal
    $ rbenv rehash
    
  3. インストールするRailsのバージョン確認

    terminal
    $ gem search -r rails | grep "^rails ("
    
    実行結果
    rails (4.1.6)
    
  4. Railsインストール

    terminal
    $ gem install rails
    

    バージョンを指定する場合は --version オプションを付ける。

    terminal
    $ gem install rails --version 4.1.6
    

    〜コーヒータイム〜
    MacBookAir13inchi(2012)でやったときは11分くらい

    --no-ri --no-rdoc をオプションで付けるとドキュメントのインストールを省略できるので少しは早くなるかも。

    実行結果
    .
    .
    .
    Done installing documentation for actionmailer, actionpack, actionview, activemodel, activerecord, activesupport, arel, builder, erubis, hike, i18n, mail, mime-types, minitest, rack, rack-test, rails, railties, sprockets, sprockets-rails, thor, thread_safe, tilt, tzinfo after 417 seconds
    24 gems installed
    
    terminal
    $ source ~/.bash_profile
    
  5. アプリケーション作成

    terminal
    $ rails new cat
    

    このとき --skip-bundle を付けて bundle install を実行しないということもできる。
    すでに bundle install を実行済みであれば付けた方が早く処理がおわってよい。

    もし次のエラーが表示された場合は

    実行結果
    .
    .
    .
    Gem::Ext::BuildError: ERROR: Failed to build gem native extension.
    
        /home/vagrant/.rbenv/versions/2.1.3/bin/ruby extconf.rb 
    checking for sqlite3.h... no
    sqlite3.h is missing. Try 'port install sqlite3 +universal',
    'yum install sqlite-devel' or 'apt-get install libsqlite3-dev'
    and check your shared library search path (the
    location where your sqlite3 shared library is located).
    *** extconf.rb failed ***
    Could not create Makefile due to some reason, probably lack of necessary
    libraries and/or headers.  Check the mkmf.log file for more details.  You may
    need configuration options.
    .
    .
    .
    

    sqliteをインストールする。

    terminal
    $ sudo yum -y install sqlite-devel
    
    実行結果
    .
    .
    .
    インストール:
      sqlite-devel.x86_64 0:3.7.17-4.el7                                                                
    
    完了しました!
    
  6. Gemfile編集

    terminal
    $ vi cat/Gemfile
    

    15行目の # gem 'therubyracer', platforms: :ruby のコメントアウトを外す。

    Gemfile
    01  source 'https://rubygems.org'
    02  
    03  
    04  # Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
    05  gem 'rails', '4.1.2'
    06  # Use sqlite3 as the database for Active Record
    07  gem 'sqlite3'
    08  # Use SCSS for stylesheets
    09  gem 'sass-rails', '~> 4.0.3'
    10  # Use Uglifier as compressor for JavaScript assets
    11  gem 'uglifier', '>= 1.3.0'
    12  # Use CoffeeScript for .js.coffee assets and views
    13  gem 'coffee-rails', '~> 4.0.0'
    14  # See https://github.com/sstephenson/execjs#readme for more supported runtimes
    15  gem 'therubyracer',  platforms: :ruby
    16  
    17  # Use jquery as the JavaScript library
    18  gem 'jquery-rails'
    .
    .
    .
    
  7. Gemfileを編集したのでbundleinstall

    terminal
    cat/bin/bundle install
    

    次のエラーが表示されたら

    terminal
    Gem::Ext::BuildError: ERROR: Failed to build gem native extension.
    
        /home/vagrant/.rbenv/versions/2.1.3/bin/ruby extconf.rb 
    creating Makefile
    
    make "DESTDIR=" clean
    
    make "DESTDIR="
    compiling rr.cpp
    make: g++: コマンドが見つかりませんでした
    make: *** [rr.o] エラー 127
    
    make failed, exit code 2
    
    Gem files will remain installed in /home/vagrant/.rbenv/versions/2.1.3/lib/ruby/gems/2.1.0/gems/therubyracer-0.10.2 for inspection.
    Results logged to /home/vagrant/.rbenv/versions/2.1.3/lib/ruby/gems/2.1.0/extensions/x86_64-linux/2.1.0-static/therubyracer-0.10.2/gem_make.out
    An error occurred while installing therubyracer (0.12.1), and Bundler cannot continue.
    Make sure that `gem install therubyracer -v '0.12.1'` succeeds before bundling.
    

    gcc++が無くてjavascriptエンジン(v8)のコンパイルに失敗している可能性があるためインストールする。

    terminal
    $ sudo yum -y install gcc-c++
    
  8. Server起動

    terminal
    $ cd cat
    $ rails s
    

    ※ Rails4.2 以上の場合は $rails s -b 0.0.0.0 とする。

  9. 動作確認

    http://192.168.33.10:3000 にアクセスしてこんな感じに表示できればOK!

    81afc098-69a7-6755-f012-9cca444d0438.png

参考URL

293
282
5

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
293
282