ponkiti's blog

主に自分用、イベント参加メモや備忘録として利用

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のユーザ登録

https://www.heroku.com/

f:id:pyoonn:20141022105114p:plain

toolbeltのインストール

herokuコマンドを使えるようにするため、toolbeltをインストールしておく。

https://toolbelt.heroku.com/standalone

f:id:pyoonn:20141022104809p:plain

f:id:pyoonn:20141022104909p:plain

表示されたコマンドを実行する。

[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のダッシュボードにも新規作成したアプリケーション画面が作成される。

f:id:pyoonn:20141022114343p:plain

アプリケーション名は変更可能

アプリケーション名に使用可能な文字列

使用可能なのは小文字、数字、ダッシュ(-)のみで、アンダーバー(_)は指定できない。

下記は、使用可能な文字列以外を指定した場合のエラー。

[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のダッシュボード上でもアプリケーション名の変更が確認できた。

f:id:pyoonn:20141022114540p:plain

Settings画面でアプリケーション名を変更することも可能。

f:id:pyoonn:20141022114633p:plain

参考

複数のPCでリモートリポジトリを共有し、各ローカルリポジトリでgit cloneやgit pushを実行する

自宅PCにてRailsアプリケーション環境を作成し、それをGitHubリポジトリにpushしたが、会社PCでも同じリポジトリの内容を共有できれば楽だなーと思ったので、そうしてみた。

やりたいこと

  1. リモートリポジトリ(GitHub)の内容をpush元とは異なるローカルリポジトリに反映する。
  2. push元とは異なるローカルリポジトリからリモートリポジトリへpushする。

ローカルリポジトリの環境

自宅PC・会社PCともにVagrantで立ち上げた仮想マシン上で管理する。

1. リモートリポジトリの内容を別のローカルリポジトリへ反映

GitHubリポジトリ画面で「SSH clone URL」をコピーする。

f:id:pyoonn:20141021154409p:plain

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_workspace」という名称でSSH Keysを登録した。
  • PCごとにSSH Keysを登録する必要があるらしい。

f:id:pyoonn:20141021150505p:plain

ファイルの編集

例として、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

リモートリポジトリを確認

リモートリポジトリに変更が反映された!

f:id:pyoonn:20141021162941p:plain

参考

Ruby on Rails チュートリアル「第1章 ゼロからデプロイまで」の環境構築メモ(2) 〜SSHの公開鍵を作成してGitHubにpushするまで〜

GitHubリポジトリの作成

「New repository」を選択する。

f:id:pyoonn:20141020175217p:plain

「Repository name」を設定し、「Create repository」ボタンを押す。

f:id:pyoonn:20141020160738p:plain

秘密鍵と公開鍵の作成

~/.sshディレクトリにid_rsaid_rsa.pubの2つの鍵がなければ、鍵を作成する。

[vagrant@localhost first_app]$ ls ~/.ssh

鍵の作成には、ssh-keygenを実行する。

  1. 鍵の保存先を聞かれるが、/home/vagrant/.ssh/id_rsaのままで問題なければ、Enterを入力する。
  2. 次に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」を選択する。

f:id:pyoonn:20141020161544p:plain

「Add SSH key」を選択する。

f:id:pyoonn:20141020164656p:plain

先程作成しておいたid_rsa.pubの中身をコピーし、SSH Keys設定画面のKey欄に貼り付ける。

[vagrant@localhost first_app]$ vi ~/.ssh/id_rsa.pub

Title欄は任意のテキストを入力し、「Add key」を選択する。

f:id:pyoonn:20141020165227p:plain

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に変更する。

f:id:pyoonn:20141020173716p:plain

.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.

無事、GitHub上のリポジトリに反映された!

f:id:pyoonn:20141020174410p:plain

参考

Ruby on Rails チュートリアル「第1章 ゼロからデプロイまで」の環境構築メモ(1) 〜Railsサーバ起動まで〜

環境

インストール対象

2014年10月19日時点でのRuby on Rails チュートリアルではそれぞれ下記のバージョンを使っているので、それに倣うこととする。

VagrantRailsをインストールするための環境を作る

任意のディレクトリ(今回は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
    • ralis serverは3000番ポートを使っているため、仮想マシンの3000番ポートをホストOS上(Mac)の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して、仮想マシンSSH接続する。

$ 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 updatebundle 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

f:id:pyoonn:20141017171811p:plain

参考

*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

接続できた!

f:id:pyoonn:20141017171811p:plain

上記ページに接続できると、コマンドラインツール上に下記が表示される。

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)

参考