nokogiriがインストールできずにbundle installできない
Ruby on Rails チュートリアル第3章の初っ端からbundle install
ができず、つまってしまった。
エラー内容
[vagrant@localhost sample_app]$ bundle install --without production Fetching gem metadata from https://rubygems.org/......... Resolving dependencies... Using rake 10.3.2 (省略) Using bundler 1.7.4 Installing mini_portile 0.6.0 Building nokogiri using packaged libraries. Building libxml2-2.8.0 for nokogiri with the following patches applied: - 0001-Fix-parser-local-buffers-size-problems.patch - 0002-Fix-entities-local-buffers-size-problems.patch - 0003-Fix-an-error-in-previous-commit.patch - 0004-Fix-potential-out-of-bound-access.patch - 0005-Detect-excessive-entities-expansion-upon-replacement.patch - 0006-Do-not-fetch-external-parsed-entities.patch - 0007-Enforce-XML_PARSER_EOF-state-handling-through-the-pa.patch - 0008-Improve-handling-of-xmlStopParser.patch - 0009-Fix-a-couple-of-return-without-value.patch - 0010-Keep-non-significant-blanks-node-in-HTML-parser.patch - 0011-Do-not-fetch-external-parameter-entities.patch ************************************************************************ IMPORTANT! Nokogiri builds and uses a packaged version of libxml2. If this is a concern for you and you want to use the system library instead, abort this installation process and reinstall nokogiri as follows: gem install nokogiri -- --use-system-libraries If you are using Bundler, tell it to use the option: bundle config build.nokogiri --use-system-libraries bundle install However, note that nokogiri does not necessarily support all versions of libxml2. For example, libxml2-2.9.0 and higher are currently known to be broken and thus unsupported by nokogiri, due to compatibility problems and XPath optimization bugs. ************************************************************************ Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension. /home/vagrant/.rbenv/versions/2.0.0-p0/bin/ruby extconf.rb Building nokogiri using packaged libraries. checking for iconv.h... yes checking for iconv_open() in iconv.h... yes Building libxml2-2.8.0 for nokogiri with the following patches applied: - 0001-Fix-parser-local-buffers-size-problems.patch - 0002-Fix-entities-local-buffers-size-problems.patch - 0003-Fix-an-error-in-previous-commit.patch - 0004-Fix-potential-out-of-bound-access.patch - 0005-Detect-excessive-entities-expansion-upon-replacement.patch - 0006-Do-not-fetch-external-parsed-entities.patch - 0007-Enforce-XML_PARSER_EOF-state-handling-through-the-pa.patch - 0008-Improve-handling-of-xmlStopParser.patch - 0009-Fix-a-couple-of-return-without-value.patch - 0010-Keep-non-significant-blanks-node-in-HTML-parser.patch - 0011-Do-not-fetch-external-parameter-entities.patch ************************************************************************ IMPORTANT! Nokogiri builds and uses a packaged version of libxml2. If this is a concern for you and you want to use the system library instead, abort this installation process and reinstall nokogiri as follows: gem install nokogiri -- --use-system-libraries If you are using Bundler, tell it to use the option: bundle config build.nokogiri --use-system-libraries bundle install However, note that nokogiri does not necessarily support all versions of libxml2. For example, libxml2-2.9.0 and higher are currently known to be broken and thus unsupported by nokogiri, due to compatibility problems and XPath optimization bugs. ************************************************************************ Extracting libxml2-2.8.0.tar.gz into tmp/x86_64-unknown-linux-gnu/ports/libxml2/2.8.0... OK Running patch with /home/vagrant/.rbenv/versions/2.0.0-p0/lib/ruby/gems/2.0.0/gems/nokogiri-1.6.3.1/ports/patches/libxml2/0001-Fix-parser-local-buffers-size-problems.patch... Running 'patch' for libxml2 2.8.0... ERROR, review 'tmp/x86_64-unknown-linux-gnu/ports/libxml2/2.8.0/patch.log' to see what happened. *** 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. Provided configuration options: --with-opt-dir --without-opt-dir --with-opt-include --without-opt-include=${opt-dir}/include --with-opt-lib --without-opt-lib=${opt-dir}/lib --with-make-prog --without-make-prog --srcdir=. --curdir --ruby=/home/vagrant/.rbenv/versions/2.0.0-p0/bin/ruby --help --clean --use-system-libraries --enable-static --disable-static --with-zlib-dir --without-zlib-dir --with-zlib-include --without-zlib-include=${zlib-dir}/include --with-zlib-lib --without-zlib-lib=${zlib-dir}/lib --enable-cross-build --disable-cross-build /home/vagrant/.rbenv/versions/2.0.0-p0/lib/ruby/gems/2.0.0/gems/mini_portile-0.6.0/lib/mini_portile.rb:279:in `block in execute': Failed to complete patch task (RuntimeError) from /home/vagrant/.rbenv/versions/2.0.0-p0/lib/ruby/gems/2.0.0/gems/mini_portile-0.6.0/lib/mini_portile.rb:271:in `chdir' from /home/vagrant/.rbenv/versions/2.0.0-p0/lib/ruby/gems/2.0.0/gems/mini_portile-0.6.0/lib/mini_portile.rb:271:in `execute' from extconf.rb:282:in `block in patch' from extconf.rb:279:in `each' from extconf.rb:279:in `patch' from /home/vagrant/.rbenv/versions/2.0.0-p0/lib/ruby/gems/2.0.0/gems/mini_portile-0.6.0/lib/mini_portile.rb:108:in `cook' from extconf.rb:253:in `block in process_recipe' from extconf.rb:154:in `tap' from extconf.rb:154:in `process_recipe' from extconf.rb:423:in `<main>' Gem files will remain installed in /home/vagrant/.rbenv/versions/2.0.0-p0/lib/ruby/gems/2.0.0/gems/nokogiri-1.6.3.1 for inspection. Results logged to /home/vagrant/.rbenv/versions/2.0.0-p0/lib/ruby/gems/2.0.0/gems/nokogiri-1.6.3.1/ext/nokogiri/gem_make.out An error occurred while installing nokogiri (1.6.3.1), and Bundler cannot continue. Make sure that `gem install nokogiri -v '1.6.3.1'` succeeds before bundling.
パッケージをインストール
[vagrant@localhost sample_app]$ sudo yum install libxml2-devel libxslt-devel (省略) Complete!
nokogiriをインストール
[vagrant@localhost sample_app]$ gem install nokogiri (省略) Gem files will remain installed in /home/vagrant/.rbenv/versions/2.0.0-p0/lib/ruby/gems/2.0.0/gems/nokogiri-1.6.3.1 for inspection. Results logged to /home/vagrant/.rbenv/versions/2.0.0-p0/lib/ruby/gems/2.0.0/gems/nokogiri-1.6.3.1/ext/nokogiri/gem_make.out
再度bundle install
[vagrant@localhost sample_app]$ bundle install --without production Fetching gem metadata from https://rubygems.org/......... Resolving dependencies... Using rake 10.3.2 (省略) Installing nokogiri 1.6.0 (省略) Your bundle is complete! Gems in the group production were not installed. Use `bundle show [gemname]` to see where a bundled gem is installed. Post-install message from capybara: IMPORTANT! Some of the defaults have changed in Capybara 2.1. If you're experiencing failures, please revert to the old behaviour by setting: Capybara.configure do |config| config.match = :one config.exact_options = true config.ignore_hidden_elements = true config.visible_text_only = true end If you're migrating from Capybara 1.x, try: Capybara.configure do |config| config.match = :prefer_exact config.ignore_hidden_elements = false end Details here: http://www.elabs.se/blog/60-introducing-capybara-2-1
bundle install
できた!
以前も同じようなエラーが出て、その時はXcodeのcommand line developer toolsをインストールしたら解決したんだが・・・。nokogiri問題について後で調べておきたい。
Ruby on Rails チュートリアル「第1章 ゼロからデプロイまで」の環境構築メモ(3) 〜Herokuにデプロイする〜
Herokuのユーザ登録
toolbeltのインストール
heroku
コマンドを使えるようにするため、toolbeltをインストールしておく。
https://toolbelt.heroku.com/standalone
表示されたコマンドを実行する。
[vagrant@localhost first_app]$ wget -qO- https://toolbelt.heroku.com/install.sh | sh This script requires superuser access to install software. You will be prompted for your password by sudo. Add the Heroku CLI to your PATH using: $ echo 'PATH="/usr/local/heroku/bin:$PATH"' >> ~/.profile Installation complete
次にPATHを通すが、CentOSの場合は~/.bash_profile
に追記すること。
[vagrant@localhost first_app]$ echo 'PATH="/usr/local/heroku/bin:$PATH"' >> ~/.bash_profile [vagrant@localhost first_app]$ source ~/.bash_profile
heroku
コマンドが有効か確認する。
[vagrant@localhost first_app]$ heroku --version heroku-toolbelt/3.13.0 (x86_64-linux) ruby/2.0.0
Railsチュートリアルに合わせた事前処理
この記事に沿っているので、Herokuにデプロイするだけであればスキップしていい。
Gemfileの編集
RailsがHerokuのPostgreSQLと通信できるよう、Gemfileの編集をしておく。
[vagrant@localhost first_app]$ vi Gemfile [vagrant@localhost first_app]$ cat Gemfile source 'https://rubygems.org' ruby '2.0.0' #ruby-gemset=railstutorial_rails_4_0 gem 'rails', '4.0.5' group :development do gem 'sqlite3', '1.3.8' end gem 'sass-rails', '4.0.2' gem 'uglifier', '2.1.1' gem 'coffee-rails', '4.0.1' gem 'jquery-rails', '3.0.4' gem 'turbolinks', '1.1.1' gem 'jbuilder', '1.0.2' gem 'therubyracer' group :doc do gem 'sdoc', '0.3.20', require: false end # Railsチュートリアル(リスト1.9) group :production do gem 'pg', '0.15.1' gem 'rails_12factor', '0.0.2' end
bundle install
本番用のgemをローカルの環境にインストールしないよう--without production
オプションをつけて実行する。
[vagrant@localhost first_app]$ bundle install --without production Fetching gem metadata from https://rubygems.org/.......... Resolving dependencies... Using rake 10.3.2 (省略) Using uglifier 2.1.1 Your bundle is complete! Gems in the group production were not installed. Use `bundle show [gemname]` to see where a bundled gem is installed.
git commit
Gemfile.lockの更新情報をコミットしておく。
[vagrant@localhost first_app]$ git commit -a -m "Update Gemfile.lock for Heroku" [master 119a4fe] Update Gemfile.lock for Heroku 2 files changed, 14 insertions(+), 0 deletions(-)
herokuにログイン
秘密鍵と公開鍵があることが前提なので、未作成の場合は環境構築メモ(2) のように「秘密鍵と公開鍵の作成」を行なう。
Herokuに登録済みのメールアドレスとパスワードを入力する。
[vagrant@localhost first_app]$ heroku login Enter your Heroku credentials. Email: メールアドレス Password (typing will be hidden): Your Heroku account does not have a public ssh key uploaded. Found an SSH public key at /home/vagrant/.ssh/id_rsa.pub Would you like to upload it to Heroku? [Yn] y Uploading SSH public key /home/vagrant/.ssh/id_rsa.pub... done Authentication successful.
herokuに新規アプリケーションを作成
Herokuにデプロイしたアプリケーションの内容は、heroku create
で生成されたアドレスにアクセスすると確認できる。
[vagrant@localhost first_app]$ heroku create Creating lit-ocean-8795... done, stack is cedar http://lit-ocean-8795.herokuapp.com/ | git@heroku.com:lit-ocean-8795.git Git remote heroku added
herokuにリポジトリをpush
[vagrant@localhost first_app]$ git push heroku master The authenticity of host 'heroku.com (50.19.85.156)' can't be established. RSA key fingerprint is XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added 'heroku.com,50.19.85.156' (RSA) to the list of known hosts. Initializing repository, done. Counting objects: 67, done. Compressing objects: 100% (53/53), done. Writing objects: 100% (67/67), 14.53 KiB, done. Total 67 (delta 6), reused 57 (delta 2) (省略) To git@heroku.com:lit-ocean-8795.git * [new branch] master -> master
Herokuのダッシュボードにも新規作成したアプリケーション画面が作成される。
アプリケーション名は変更可能
アプリケーション名に使用可能な文字列
使用可能なのは小文字、数字、ダッシュ(-
)のみで、アンダーバー(_
)は指定できない。
下記は、使用可能な文字列以外を指定した場合のエラー。
[vagrant@localhost first_app]$ heroku rename rubyonrail_stutorial_lesson Renaming lit-ocean-8795 to rubyonrail_stutorial_lesson... failed ! Name must start with a letter and can only contain lowercase letters, numbers, and dashes.
ユニークなアプリケーション名を指定
Heroku内ですでに使用されているアプリケーション名は指定できない。
[vagrant@localhost first_app]$ heroku rename rubyonrailstutorial Renaming lit-ocean-8795 to rubyonrailstutorial... failed ! Name is already taken
アプリケーション名の変更完了
下記は、アプリケーション名が無事変更できた時のメッセージ。
[vagrant@localhost first_app]$ heroku rename rubyonrailstutoriallesson Renaming lit-ocean-8795 to rubyonrailstutoriallesson... done http://rubyonrailstutoriallesson.herokuapp.com/ | git@heroku.com:rubyonrailstutoriallesson.git Git remote heroku updated
Herokuのダッシュボード上でもアプリケーション名の変更が確認できた。
Settings画面でアプリケーション名を変更することも可能。
参考
複数のPCでリモートリポジトリを共有し、各ローカルリポジトリでgit cloneやgit pushを実行する
自宅PCにてRailsアプリケーション環境を作成し、それをGitHubのリポジトリにpushしたが、会社PCでも同じリポジトリの内容を共有できれば楽だなーと思ったので、そうしてみた。
やりたいこと
ローカルリポジトリの環境
自宅PC・会社PCともにVagrantで立ち上げた仮想マシン上で管理する。
1. リモートリポジトリの内容を別のローカルリポジトリへ反映
GitHubのリポジトリ画面で「SSH clone URL」をコピーする。
git clone
で「SSH clone URL」を指定して、リモートリポジトリの内容をローカル環境上にコピーする。
[vagrant@localhost first_app_workspace]$ git clone git@github.com:ponkiti/first_app.git Initialized empty Git repository in /home/vagrant/rails_projects/first_app_workspace/first_app/.git/ The authenticity of host 'github.com (192.30.252.130)' can't be established. RSA key fingerprint is XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added 'github.com,192.30.252.130' (RSA) to the list of known hosts. remote: Counting objects: 60, done. remote: Compressing objects: 100% (47/47), done. remote: Total 60 (delta 2), reused 60 (delta 2) Receiving objects: 100% (60/60), 13.86 KiB, done. Resolving deltas: 100% (2/2), done.
リモートリポジトリの内容がローカル環境にコピーできた。
[vagrant@localhost rails_projects]$ ls first_app
2. 別のローカルリポジトリからリモートリポジトリへpush
今回のケースでは同じRailsアプリケーションを共有したいので、Railsアプリケーションを動かす環境は自宅PC・会社PCで揃えておく必要がある。環境構築メモ(1)の 「Railsアプリケーションの作成」以外を実行しておく。
SSH Keysの作成と登録
環境構築メモ(2) と同様に、新たにリモートリポジトリの内容を反映したい環境で「秘密鍵と公開鍵の作成」と「SSH Keysの設定」を行なう。
ファイルの編集
例として、first_appディレクトリにtest_fileを作成したとする。
git add
インデックスにtest_fileを追加する。
[vagrant@localhost first_app]$ git add test_file
git status
[vagrant@localhost first_app]$ git status # On branch master # Changes to be committed: # (use "git reset HEAD <file>..." to unstage) # # new file: test_file #
git commit
[vagrant@localhost first_app]$ git commit -m "git test workspace" [master 15deb5b] git test workspace 1 files changed, 3 insertions(+), 0 deletions(-) create mode 100644 test_file
git push
[vagrant@localhost first_app]$ git push Counting objects: 4, done. Compressing objects: 100% (2/2), done. Writing objects: 100% (3/3), 290 bytes, done. Total 3 (delta 1), reused 0 (delta 0) To git@github.com:ponkiti/first_app.git cfe92ba..15deb5b master -> master
リモートリポジトリを確認
リモートリポジトリに変更が反映された!
参考
Ruby on Rails チュートリアル「第1章 ゼロからデプロイまで」の環境構築メモ(2) 〜SSHの公開鍵を作成してGitHubにpushするまで〜
GitHubリポジトリの作成
「New repository」を選択する。
「Repository name」を設定し、「Create repository」ボタンを押す。
秘密鍵と公開鍵の作成
~/.ssh
ディレクトリにid_rsa
とid_rsa.pub
の2つの鍵がなければ、鍵を作成する。
[vagrant@localhost first_app]$ ls ~/.ssh
鍵の作成には、ssh-keygen
を実行する。
- 鍵の保存先を聞かれるが、
/home/vagrant/.ssh/id_rsa
のままで問題なければ、Enter
を入力する。 - 次にpassphraseを2回聞かれるが、「鍵を使うときにパスフレーズを入力したくない場合は、パスフレーズを空のままに」しておく。
[vagrant@localhost first_app]$ ssh-keygen Generating public/private rsa key pair. Enter file in which to save the key (/home/vagrant/.ssh/id_rsa): Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /home/vagrant/.ssh/id_rsa. Your public key has been saved in /home/vagrant/.ssh/id_rsa.pub. The key fingerprint is: (省略)
秘密鍵(id_rsa)と公開鍵(id_rsa.pub)が作成されていることを確認する。
[vagrant@localhost first_app]$ ls ~/.ssh id_rsa id_rsa.pub
SSH Keysの設定
「Settings」を選択し、profile画面で「SSH keys」を選択する。
「Add SSH key」を選択する。
先程作成しておいたid_rsa.pubの中身をコピーし、SSH Keys設定画面のKey欄に貼り付ける。
[vagrant@localhost first_app]$ vi ~/.ssh/id_rsa.pub
Title欄は任意のテキストを入力し、「Add key」を選択する。
RailsプロジェクトのファイルをGitHubに登録
システムセットアップ
Gitのコミットに必要なため、GitHubに登録済みのユーザー名とメールアドレスをそれぞれ登録する。
これらの情報は~/.gitconfig
ファイルに登録される。
[vagrant@localhost first_app]$ git config --global user.name "ユーザ名" [vagrant@localhost first_app]$ git config --global user.email メールアドレス [vagrant@localhost first_app]$ vi ~/.gitconfig [vagrant@localhost first_app]$ cat ~/.gitconfig [user] name = ユーザ名 email = メールアドレス
リポジトリの作成
git init
を実行すると、.git
ディレクトリが生成される。
[vagrant@localhost first_app]$ git init Initialized empty Git repository in /home/vagrant/rails_projects/first_app/.git/ [vagrant@localhost first_app]$ ls -all 合計 76 drwxrwxr-x 13 vagrant vagrant 4096 10月 20 08:11 2014 . drwxrwxr-x 3 vagrant vagrant 4096 10月 20 06:15 2014 .. drwxrwxr-x 7 vagrant vagrant 4096 10月 20 08:11 2014 .git -rw-rw-r-- 1 vagrant vagrant 466 10月 20 06:15 2014 .gitignore -rw-rw-r-- 1 vagrant vagrant 388 10月 20 06:16 2014 Gemfile (省略)
.gitignoreファイルの編集
Railsチュートリアルに従い、Gitの管理対象から除外するファイルを設定するため、.gitignore
ファイルを編集する。
[vagrant@localhost first_app]$ rm -rf .gitignore [vagrant@localhost first_app]$ vi .gitignore [vagrant@localhost first_app]$ cat .gitignore # Ignore bundler config. /.bundle # Ignore the default SQLite database. /db/*.sqlite3 /db/*.sqlite3-journal # Ignore all logfiles and tempfiles. /log/*.log /tmp # Ignore other unneeded files. doc/ *.swp *~ .project .DS_Store .idea .secret
インデックスへ登録
git add
は指定したファイルをインデックスに登録する。.
を指定することで、カレントディレクトリ内のすべてのファイル(サブディレクトリも含む)をインデックスに登録する。
[vagrant@localhost first_app]$ git add .
git status
はステージングエリアにあるファイルのリストを表示できる。
[vagrant@localhost first_app]$ git status # On branch master # # Initial commit # # Changes to be committed: # (use "git rm --cached <file>..." to unstage) # # new file: .gitignore # new file: Gemfile # new file: Gemfile.lock (省略)
インデックスに追加したファイルのコミット
git commit
する。-m
オプションをつけると、コミットメッセージを指定してコミットできる。
[vagrant@localhost first_app]$ git commit -m "Initialize repository" [master (root-commit) cfe92ba] Initialize repository 36 files changed, 804 insertions(+), 0 deletions(-) create mode 100644 .gitignore create mode 100644 Gemfile create mode 100644 Gemfile.lock (省略)
.git/configファイルの設定
今回はSSH Keysを設定しているので、.git/config
ファイルのremoteのプロトコルはSSHに変更する。
.git/config
ファイルのurl = https://github.com/ponkiti/first_app.git
という記述をurl = ssh://git@github.com:ponkiti/first_app.git
に変更する。
[vagrant@localhost first_app]$ vi .git/config [vagrant@localhost first_app]$ cat .git/config [core] repositoryformatversion = 0 filemode = true bare = false logallrefupdates = true [remote "origin"] url = ssh://git@github.com:ponkiti/first_app.git fetch = +refs/heads/*:refs/remotes/origin/*
リモートリポジトリへpush
ローカルレポジトリの内容をリモートリポジトリ(GitHub上に作成したリポジトリ)に反映させる。
git remote add origin git@github.com:ユーザー名/リポジトリ名.git
[vagrant@localhost first_app]$ git remote add origin git@github.com:ponkiti/first_app.git [vagrant@localhost first_app]$ git push -u origin master The authenticity of host 'github.com (192.30.252.131)' can't be established. RSA key fingerprint is XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added 'github.com,192.30.252.131' (RSA) to the list of known hosts. Counting objects: 60, done. Compressing objects: 100% (49/49), done. Writing objects: 100% (60/60), 13.86 KiB, done. Total 60 (delta 2), reused 0 (delta 0) To git@github.com:ponkiti/first_app.git * [new branch] master -> master Branch master set up to track remote branch master from origin.
参考
Ruby on Rails チュートリアル「第1章 ゼロからデプロイまで」の環境構築メモ(1) 〜Railsサーバ起動まで〜
環境
- Mac OS Ⅹ 10.9.5(Mavericks)
- VirtualBox 4.3.18
- Vagrant 1.6.5(CentOS6)
- Vagrant上の仮想マシンに入れるCentOS6には、下記のBoxを使用した。
- http://www.vagrantbox.es/
- CentOS 6.4 x86_64 Minimal (VirtualBox Guest Additions 4.3.2, Chef 11.8.0, Puppet 3.3.1)
- Vagrant上の仮想マシンに入れるCentOS6には、下記のBoxを使用した。
インストール対象
2014年10月19日時点でのRuby on Rails チュートリアルではそれぞれ下記のバージョンを使っているので、それに倣うこととする。
VagrantでRailsをインストールするための環境を作る
任意のディレクトリ(今回はruby_lessons
とした)を作成し、vagrant init
する。
$ mkdir ruby_lessons $ cd ruby_lessons $ vagrant init
Vagrantfileの設定
vagrant init
するとVagrantfileが生成されるので、下記の記述を追記する。
- config.vm.box = "CentOS64"
vagrant box add
で指定した任意のBox名を設定すること。
- config.vm.network "forwarded_port", guest: 3000, host: 3000
# -*- 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 = "CentOS64" (省略) # 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: 3000, host: 3000 (省略) end
$ vagrant up $ vagrant ssh
Rubyをインストールするための下準備
バージョンが古いRubyのアンインストール
[vagrant@localhost ~]$ sudo yum -y remove ruby
Gitのインストール
[vagrant@localhost ~]$ sudo yum -y install git
rbenvのインストール
rbenvをインストールし、PATHを通す。
[vagrant@localhost ~]$ git clone https://github.com/sstephenson/rbenv.git ~/.rbenv [vagrant@localhost ~]$ echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bash_profile [vagrant@localhost ~]$ echo 'eval "$(rbenv init -)"' >> ~/.bash_profile
~/.bash_profile
の内容を確認しておく。
[vagrant@localhost ~]$ 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/bin export PATH export PATH="$HOME/.rbenv/bin:$PATH" eval "$(rbenv init -)"
source
コマンドを実行し、rbenvのバージョン、もといrbenvコマンドが使用できるかを確認しておく。
[vagrant@localhost ~]$ source ~/.bash_profile [vagrant@localhost ~]$ rbenv --version rbenv 0.4.0-124-g07d6753
ruby-buildのインストール
[vagrant@localhost ~]$ git clone https://github.com/sstephenson/ruby-build.git ~/.rbenv/plugins/ruby-build
Rubyのインストール
rbenv install -l
コマンドでインストール可能なRubyのバージョン一覧が確認できるが、今回はRailsチュートリアルに合わせて2.0.0-p0
をインストールする。
[vagrant@localhost ~]$ rbenv install -l [vagrant@localhost ~]$ rbenv install 2.0.0-p0
rbenv global
コマンドの実行を忘れると、ruby
コマンドが効かないので注意すること。
[vagrant@localhost ~]$ rbenv global 2.0.0-p0 [vagrant@localhost ~]$ ruby -v ruby 2.0.0p0 (2013-02-24 revision 39474) [x86_64-linux]
Railsをインストールするための下準備
~/.gemrcの設定
通常、gem installすると同時にドキュメントがインストールされてしまうため、gemのインストールに時間がかかってしまう。
~/.gemrc
ファイルに--no-rdoc --no-ri
オプションを設定しておくと、以降のgemのインストール時に--no-rdoc --no-ri
オプションが効くようになり、インストールにかかる時間が短縮される。
インストールだけでなく、アップデートにも同様に--no-rdoc --no-ri
オプションを設定することができる。
[vagrant@localhost ~]$ vi ~/.gemrc [vagrant@localhost ~]$ cat ~/.gemrc install: --no-rdoc --no-ri update: --no-rdoc --no-ri
/etc/resolv.confの設定
CentOS6を使用している場合は、/etc/resolv.conf
ファイルにoptions single-request-reopen
を追記しておくこと。これを書いておかないとgem install rails
に1時間ほどかかってしまう・・・。
[vagrant@localhost ~]$ sudo vi /etc/resolv.conf [vagrant@localhost ~]$ sudo cat /etc/resolv.conf ; generated by /sbin/dhclient-script nameserver 10.0.2.3 options single-request-reopen
/etc/sysconfig/iptablesの設定
/etc/sysconfig/iptables
ファイルに-A INPUT -p tcp -m tcp --dport 3000 -j ACCEPT
を追記しておく。この記述を追加しておかないと、rails s
実行後に3000番ポートにアクセスできない。
[vagrant@localhost first_app]$ sudo vi /etc/sysconfig/iptables
「ここまでのチェックでひっかからなかったパケットは、ICMPパケット"host-prohibited"を返して接続拒否」するため、今回追記する-A INPUT -p tcp -m tcp --dport 3000 -j ACCEPT
は、-A INPUT -j REJECT --reject-with icmp-host-prohibited
よりも前の行に記述すること。
[vagrant@localhost first_app]$ sudo cat /etc/sysconfig/iptables # Firewall configuration written by system-config-firewall # Manual customization of this file is not recommended. *filter :INPUT ACCEPT [0:0] :FORWARD ACCEPT [0:0] :OUTPUT ACCEPT [0:0] -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT -A INPUT -p icmp -j ACCEPT -A INPUT -i lo -j ACCEPT -A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT -A INPUT -p tcp -m tcp --dport 3000 -j ACCEPT -A INPUT -j REJECT --reject-with icmp-host-prohibited -A FORWARD -j REJECT --reject-with icmp-host-prohibited COMMIT
iptablesに追加した内容を保存し、iptablesを再起動する。
[vagrant@localhost first_app]$ sudo service iptables save [vagrant@localhost first_app]$ sudo service iptables restart
Railsのインストール
Railsチュートリアルに合わせてRails 4.0.5
をインストールする。
[vagrant@localhost ~]$ gem install rails --version 4.0.5
インストールしたgemを有効にするため、rbenv rehash
を行う。
- gemやRubyをインストール(アンインストール)した時には、
rbenv rehash
を必ず実行しておくこと。 rbenv rehash
を自動で行うようにするには、gem install rbenv-rehash
しておくとよい。
[vagrant@localhost ~]$ rbenv rehash [vagrant@localhost ~]$ rails -v Rails 4.0.5
Railsアプリケーションの作成
rails new
コマンドを実行して、任意のディレクトリ(今回はfirst_app
ディレクトリ)にRailsアプリケーションを作成する。
[vagrant@localhost ~]$ mkdir rails_projects [vagrant@localhost ~]$ cd rails_projects/ [vagrant@localhost rails_projects]$ rails new first_app
first_app
ディレクトリに移動し、作成されたファイルを確認しておく。
[vagrant@localhost rails_projects]$ cd first_app/ [vagrant@localhost first_app]$ ls Gemfile README.rdoc app config db log test vendor Gemfile.lock Rakefile bin config.ru lib public tmp
デフォルトのGemfileのままだと最新のgemを取得してしまうため、Gemfileにはgemのバージョンをそれぞれ指定しておく。
[vagrant@localhost first_app]$ rm -rf Gemfile [vagrant@localhost first_app]$ vi Gemfile
Gemfileの設定
「Could not find a JavaScript runtime.」というエラーが出る場合、Gemfileにgem 'therubyracer'
を追記しておく。
source 'https://rubygems.org' ruby '2.0.0' #ruby-gemset=railstutorial_rails_4_0 gem 'rails', '4.0.5' group :development do gem 'sqlite3', '1.3.8' end gem 'sass-rails', '4.0.2' gem 'uglifier', '2.1.1' gem 'coffee-rails', '4.0.1' gem 'jquery-rails', '3.0.4' gem 'turbolinks', '1.1.1' gem 'jbuilder', '1.0.2' gem 'therubyracer' group :doc do gem 'sdoc', '0.3.20', require: false end
Gemfileの設定後、bundle update
とbundle install
を実行し、gemをインストールする。
[vagrant@localhost first_app]$ bundle update [vagrant@localhost first_app]$ bundle install
rails serverの起動
rails server
コマンドは省略してrails s
で実行することが可能。
[vagrant@localhost first_app]$ rails s
rails serverの起動を確認
任意のブラウザで http://localhost:3000/ にアクセスする。*1
参考
- Vagrant で Ruby on Rails の環境を構築するまでの手順 - Qiita
- Vagrantの仮想環境でrails serverで動いているアプリケーションにMacのブラウザからアクセスしてみる | Fuzz blog
- http://blog.axross.org/entry/2013/12/19/221625
- iptablesの設定
*1:20141217追記:rails serverが起動できているのに http://localhost:3000/ にアクセスできない場合、iptablesを停止(service iptables stop)して http://localhost:3000/ にアクセスできるか確認してみること。iptablesを停止した状態でアクセスできる場合、iptables(/etc/sysconfig/iptables)の設定ができていない可能性があるため、3000番ポートを許可しているかどうかを確認すること。
rails sコマンド実行後にlocalhost:3000に接続できない場合(2)
自宅PCでもRailsをインストールしたが、Railsサーバを起動させようとしてうまくいかない。
どうやらファイヤーウォールを切っていなかったのがまずかったらしい。今回仮想マシンにインストールしたのはCentOS6。下記コマンドを実行してファイアーウォールを停止させると、Railsサーバは起動する。
[vagrant@localhost ~]$ sudo service iptables stop iptables: Flushing firewall rules: [ OK ] iptables: Setting chains to policy ACCEPT: filter [ OK ] iptables: Unloading modules: [ OK ] [vagrant@localhost ~]$ sudo chkconfig iptables off
下記のように、/etc/sysconfig/iptables
ファイルに-A INPUT -p tcp -m tcp --dport 3000 -j ACCEPT
を追記しなくても問題なかった。
最初はファイアーウォールを停止させずに/etc/sysconfig/iptables
ファイルへの追記を行ったのだけど、localhost:3000に接続できず・・・。もしかしたらiptablesの再起動(service iptables restart
)ができていなかっただけなのかも。
iptablesの設定で3000番ポートを有効にしているか、元からファイアーウォールを停止しているかで、結果的にはやっていることにそこまでの違いはないけれど、iptablesの理解が薄いので頭を整理しておく必要がありそうだ。
Huluで『Doctor Who(series 6)』を見ながら作業していたが、6時間近く時間を使ってしまった・・・・。
rails sコマンド実行後にlocalhost:3000に接続できない場合
/etc/sysconfig/iptables
ファイルに-A INPUT -p tcp -m tcp --dport 3000 -j ACCEPT
という記述を追記する。
$ sudo vi /etc/sysconfig/iptables $ sudo cat /etc/sysconfig/iptables # Firewall configuration written by system-config-firewall # Manual customization of this file is not recommended. *filter :INPUT ACCEPT [0:0] :FORWARD ACCEPT [0:0] :OUTPUT ACCEPT [0:0] -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT -A INPUT -p icmp -j ACCEPT -A INPUT -i lo -j ACCEPT -A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT -A INPUT -p tcp -m tcp --dport 3000 -j ACCEPT -A INPUT -j REJECT --reject-with icmp-host-prohibited -A FORWARD -j REJECT --reject-with icmp-host-prohibited COMMIT $ exit
仮想マシンからログアウトし、Vagrantfileを下記のように修正した。
- コメントアウト
config.vm.network "private_network", ip: "192.168.33.10"
config.vm.network "forwarded_port", guest: 80, host: 8080
- 追記
config.vm.network :"forwarded_port", guest: 3000, host: 3000
# -*- 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 = "CentOS64" # 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 config.vm.network :"forwarded_port", guest: 3000, host: 3000 # 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" (省略) end
Vagrantfileの修正を反映するため、vagrant reload
コマンドを実行する。
$ vagrant reload ==> default: Attempting graceful shutdown of VM... ==> default: Clearing any previously set forwarded ports... ==> default: Clearing any previously set network interfaces... ==> default: Preparing network interfaces based on configuration... default: Adapter 1: nat ==> default: Forwarding ports... default: 3000 => 3000 (adapter 1) default: 22 => 2222 (adapter 1) ==> default: Booting VM... ==> default: Waiting for machine to boot. This may take a few minutes... default: SSH address: 127.0.0.1:2222 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: Mounting shared folders... default: /vagrant => /Users/ponkiti/Vagrant/rails_lesson ==> default: Machine already provisioned. Run `vagrant provision` or use the `--provision` ==> default: to force provisioning. Provisioners marked to run always will still run. $ vagrant ssh
仮想マシンにSSH接続し、作成済みのアプリケーションディレクトリ(今回はfirst_app)に移動し、rails s
コマンドを再実行する。
$ cd rails_projects/first_app $ rails s => Booting WEBrick => Rails 4.0.5 application starting in development on http://0.0.0.0:3000 => Run `rails server -h` for more startup options => Ctrl-C to shutdown server [2014-10-16 07:29:25] INFO WEBrick 1.3.1 [2014-10-16 07:29:25] INFO ruby 2.0.0 (2013-02-24) [x86_64-linux] [2014-10-16 07:29:25] INFO WEBrick::HTTPServer#start: pid=2020 port=3000
接続できた!
上記ページに接続できると、コマンドラインツール上に下記が表示される。
Started GET "/" for 10.0.2.2 at 2014-10-16 07:29:29 +0000 Processing by Rails::WelcomeController#index as HTML Rendered /home/vagrant/.rbenv/versions/2.0.0-p0/lib/ruby/gems/2.0.0/gems/railties-4.0.5/lib/rails/templates/rails/welcome/index.html.erb (2.4ms) Completed 200 OK in 43ms (Views: 42.9ms | ActiveRecord: 0.0ms)