カタカタブログ

SIerで働くITエンジニアがカタカタした記録を残す技術ブログ。Java, Oracle Database, Linuxが中心です。たまに数学やデータ分析なども。

Raspberry Pi 2 にRuby on Rails 4 環境を構築してみた

Raspberry Pi 2にRuby on Rails 4の環境を作ってみたので、構築手順をメモ。まあ例によってRaspberry Pi 特有の事情はほとんどなく、Rubyのインストール(ビルド)には結構時間がかかった以外は、普通のサーバにRails環境を構築するのとほとんど変わらなかった。

検証に使ったバージョンは以下。

  • ruby 2.2.2
  • rbenv 0.4.0-148
  • rails 4.2.1
  • sqlite 3.7.13

Rubyインストール

Raspberry pi 2デフォルトのRubyは1.9.3と古かったため、最新版をインストールする。rbenvをまず入れて、rbenvから最新版Rubyをインストールする

デフォルトのRubyを確認

pi@raspberrypi~ $ ruby -v
ruby 1.9.3p194 (2012-04-20 revision 35410) [arm-linux-eabihf]

gitはデフォルトのものをそのまま使う。

pi@raspberrypi~ $ git --version
git version 1.7.10.4

rbenvをpiユーザの$HOME/.rbenvにインストールする。
rbenvの公式の手順では.bash_profileに設定を追記するが、piユーザの.bashrcにデフォルトでいろいろ設定されており、
.bash_profileを書くと.bashrcが読まれないので、こちらに.bashrcに追記することにする。(.bash_profileで.bashrcを読む処理を追記してもよいが。)

pi@raspberrypi~ $ git clone https://github.com/sstephenson/rbenv.git ~/.rbenv
Cloning into '/home/pi/.rbenv'...
remote: Counting objects: 2057, done.
remote: Total 2057 (delta 0), reused 0 (delta 0), pack-reused 2057
Receiving objects: 100% (2057/2057), 344.17 KiB | 322 KiB/s, done.
Resolving deltas: 100% (1272/1272), done.
pi@raspberrypi~ $ echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc
pi@raspberrypi~ $ echo 'eval "$(rbenv init -)"' >> ~/.bashrc

piユーザの.bash_profileを読み直し、rbenvが使えるようになったことを確認する。

pi@raspberrypi~ $ . .bash_profile
pi@raspberrypi~ $ rbenv
rbenv 0.4.0-148-g5b9e4f0
(・・・略)

Rubyをインストールするため、ruby-buildを追加する。

pi@raspberrypi~ $ git clone https://github.com/sstephenson/ruby-build.git ~/.rbenv/plugins/ruby-build
Cloning into '/home/pi/.rbenv/plugins/ruby-build'...
remote: Counting objects: 4548, done.
remote: Total 4548 (delta 0), reused 0 (delta 0), pack-reused 4548
Receiving objects: 100% (4548/4548), 859.14 KiB | 176 KiB/s, done.
Resolving deltas: 100% (2356/2356), done.

rbenvからRubyをインストールする。まず、使用可能なRubyのバージョンを確認する。

pi@raspberrypi~ $ rbenv install -l

現時点の最新版である2.2.2をインストールする。

pi@raspberrypi~ $ rbenv install 2.2.2
Downloading ruby-2.2.2.tar.gz...
-> http://dqw8nmjcqpjn7.cloudfront.net/5ffc0f317e429e6b29d4a98ac521c3ce65481bfd22a8cf845fa02a7b113d9b44
Installing ruby-2.2.2...BUILD FAILED (Raspbian GNU/Linux 7 using ruby-build 20150519-3-ge932d47)
Inspect or clean up the working tree at /tmp/ruby-build.20150530131454.3188Results logged to /tmp/ruby-build.20150530131454.3188.log
Last 10 log lines:
                              minitest-5.4.3.gem
                              power_assert-0.2.2.gem
                              test-unit-3.0.8.gem
installing rdoc:              /home/pi/.rbenv/versions/2.2.2/share/ri/2.2.0/system
installing capi-docs:         /home/pi/.rbenv/versions/2.2.2/share/doc/ruby
The Ruby openssl extension was not compiled. Missing the OpenSSL lib?
Configure options used:
  --prefix=/home/pi/.rbenv/versions/2.2.2
  LDFLAGS=-L/home/pi/.rbenv/versions/2.2.2/lib
  CPPFLAGS=-I/home/pi/.rbenv/versions/2.2.2/include 

インストールに失敗してしまった。どうやらopensslのライブラリが足りないよう。

pi@raspberrypi~ $ sudo apt-get update
pi@raspberrypi~ $ openssl version
OpenSSL 1.0.1e 11 Feb 2013

OpenSSLは入っている。OpenSSLのライブラリである"libssl-dev”を確認する。

pi@raspberrypi~ $ dpkg -l libssl-dev*
dpkg-query: libssl-dev* に一致するパッケージが見つかりません

こっちはなさそうなので、apt-getでインストールする。

pi@raspberrypi~ $ sudo apt-get install libssl-dev

インストールされたことを確認。

pi@raspberrypi~ $ dpkg -l libssl-dev
要望=(U)不明/(I)インストール/(R)削除/(P)完全削除/(H)保持
| 状態=(N)無/(I)インストール済/(C)設定/(U)展開/(F)設定失敗/(H)半インストール/(W)トリガ待ち/(T)トリガ保留
|/ エラー?=(空欄)無/(R)要再インストール (状態,エラーの大文字=異常)
||/ 名前             バージョ   アーキテ   説明
+++-==================-==============-==============-==========================================
ii  libssl-dev         1.0.1e-2+rvt+d armhf          SSL development libraries, header files an

再度Rubyのインストール。

pi@raspberrypi~ $ rbenv install 2.2.2
(数時間待つ)
pi@raspberrypi:~$ rbenv versions
* system (set by /home/pi/.rbenv/version)
  2.2.2

今度は無事インストールされた!

rbenv globalで2.2.2に切り替え、rubyが切り替わったことを確認する。

pi@raspberrypi~ $ rbenv global 2.2.2
pi@raspberrypi~ $ ruby -v
ruby 2.2.2p95 (2015-04-13 revision 50295) [armv7l-linux-eabihf]

これでRubyが最新化された!

Railsインストール

続いてRails 4をインストールする。
まず、bundlerをインストール。

pi@raspberrypi~ $ rbenv exec gem install bundler
Fetching: bundler-1.10.2.gem (100%)
Successfully installed bundler-1.10.2
Parsing documentation for bundler-1.10.2
Installing ri documentation for bundler-1.10.2
Done installing documentation for bundler after 59 seconds
1 gem installed

railsをインストールする。

pi@raspberrypi~ $ gem install rails --no-ri --no-rdoc
pi@raspberrypi~ $ rails -v
Rails 4.2.1

Rails 4.2.1がインストールできたことを確認!

データベース(SQLite3)と関連ライブラリをインストールする。

pi@raspberrypi~ $ sudo apt-get install sqlite3 ruby-dev libsqlite3-dev libsqlite3-ruby
pi@raspberrypi~ $ sqlite3 -version
3.7.13 2012-06-11 02:05:22 f5b5a13f7394dc143aa136f1d4faba6839eaa6dc

これでRuby on Rails 4の環境が整った!

サーバ起動

早速動くか確認のため、サンプルアプリを作って画面が見れるか確認する。

pi@raspberrypi~ $ mkdir rails
pi@raspberrypi~ $ cd rails/
pi@raspberrypi~/rails $ rails new myapp

まずはサーバを起動させてみる。

pi@raspberrypi~/rails/myapp $ rails s
/home/pi/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/execjs-2.5.2/lib/execjs/runtimes.rb:48:in `autodetect': Could not find a JavaScript runtime. See https://github.com/rails/execjs for a list of available runtimes. (ExecJS::RuntimeUnavailable)
        from /home/pi/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/execjs-2.5.2/lib/execjs.rb:5:in `<module:ExecJS>'

JavaScriptのruntimeがないためエラーになる。Gemfileを修正し、therubyracerをコメントインし、bundle installする。

pi@raspberrypi~/rails/myapp $ vi Gemfile
以下の行をコメントイン

gem 'therubyracer', platforms: :ruby
pi@raspberrypi~/rails/myapp $ bundle install

もう一度起動させてみる。

pi@raspberrypi~/rails/myapp $ rails s
    Sorry, you can't use byebug without Readline. To solve this, you need to
    rebuild Ruby with Readline support. If using Ubuntu, try `sudo apt-get
    install libreadline-dev` and then reinstall your Ruby.
bin/rails:6: warning: already initialized constant APP_PATH
/home/pi/rails/myapp/bin/rails:6: warning: previous definition of APP_PATH was here
Usage: rails COMMAND [ARGS]
The most common rails commands are:
 generate    Generate new code (short-cut alias: "g")
 console     Start the Rails console (short-cut alias: "c")
 server      Start the Rails server (short-cut alias: "s")
 dbconsole   Start a console for the database specified in config/database.yml
             (short-cut alias: "db")
 new         Create a new Rails application. "rails new my_app" creates a
             new application called MyApp in "./my_app"
In addition to those, there are:
 destroy      Undo code generated with "generate" (short-cut alias: "d")
 plugin new   Generates skeleton for developing a Rails plugin
 runner       Run a piece of code in the application environment (short-cut alias: "r")
All commands can be run with -h (or --help) for more information.

今度はlibreadline-devというライブラリが足りないらしいので、Gemfileに以下の行を追記。

gem 'rb-readline'

bundle install

pi@raspberrypi~/rails/myapp $ bundle install

サーバを起動させる。

pi@raspberrypi~/rails/myapp $ rails s
=> Booting WEBrick
=> Rails 4.2.1 application starting in development on http://localhost:3000
=> Run `rails server -h` for more startup options
=> Ctrl-C to shutdown server
[2015-05-31 13:32:18] INFO  WEBrick 1.3.1
[2015-05-31 13:32:18] INFO  ruby 2.2.2 (2015-04-13) [armv7l-linux-eabihf]
[2015-05-31 13:32:18] INFO  WEBrick::HTTPServer#start: pid=28158 port=3000

今度は正常に起動したよう!
確認のため、Macから以下のURLにアクセス(raspiはMacのhostsでRapberry PiのIPアドレスに解決している)。
http://raspi:3000

しかし、まだ画面が見れなかった。
起動ログを見ると、localhostでリッスンしているようだったので、rails sの-bオプションで0.0.0.0 (全て)の接続元を指定するように変更する。
Ctrl-Cでサーバを停止して、-bオプションをつけてサーバ起動する。

pi@raspberrypi~/rails/myapp $ rails s -b 0.0.0.0
=> Booting WEBrick
=> Rails 4.2.1 application starting in development on http://0.0.0.0:3000
=> Run `rails server -h` for more startup options
=> Ctrl-C to shutdown server
[2015-05-31 13:40:10] INFO  WEBrick 1.3.1
[2015-05-31 13:40:10] INFO  ruby 2.2.2 (2015-04-13) [armv7l-linux-eabihf]
[2015-05-31 13:40:10] INFO  WEBrick::HTTPServer#start: pid=28484 port=3000

http://raspi:3000 にアクセス
f:id:osn_th:20150606152112p:plain
正常にアプリケーションサーバに接続できた!

アプリケーション作成

サーバが動いて画面が見れたので、最後にサンプルアプリを作って、DB処理までちゃんと動くことを確認する。
Scaffoldを作成する。

pi@raspberrypi~/rails/myapp $ rails generate scaffold User user_id name:string

DBのマイグレーションを行う。

pi@raspberrypi~/rails/myapp $ rake db:migrate
== 20150606055214 CreateUsers: migrating ======================================
-- create_table(:users)
   -> 0.0120s
== 20150606055214 CreateUsers: migrated (0.0128s) =============================

サーバを再起動する。

pi@raspberrypi~/rails/myapp $ rails s -b 0.0.0.0

以下にアクセスする。
http://raspi:3000/users

サンプル・アプリにアクセスできた。
さらにDB処理も正しく行えることを確認!
f:id:osn_th:20150606152109p:plain

まとめ

以上、Raspberry Pi 2にRuby on Rails 4の環境を構築してみた。手順は普通のサーバと変わらないものの、ビルドなどはやはり昨今のマシンと比べると非力なため、Rubyのビルドなどには思ったより時間がかかる結果となった。
ただ、サーバとして起動してしまえば自分ひとりで画面を見る分にはほとんど十分な性能であり、家庭内サーバで動くWebアプリくらいであれば実用に耐えるものだと思う。

以上!

関連記事