Hateburo: kazeburo hatenablog

SRE / 運用系小姑 / Goを書くPerl Monger

HerokuでSinatraのアプリを「Rhebok」で起動する

Unicornの2倍のパフォーマンス発揮するRackサーバ「Rhebok」をherokuで動かしてみる

アプリケーションは

heroku で Sinatra のアプリを動かす - Please Sleep

を参考にさせて頂きました。

Gemfile

まずGemfileを用意します

$ cat Gemfile
source 'https://rubygems.org'
ruby "2.1.5"
gem 'sinatra'
gem 'gctools'
gem 'rhebok'

rubyのバージョンは2.1系を使い、gctoolsもいれます。Rhebokはgctoolsに含まれるGC::OOBを利用し、リクエスト処理終了後(Out Of Band)のGCを効率的に行います。

tmm1/gctools · GitHub

日本語訳: Ruby 2.1: Out-of-Band GC — sawanoboly.net

app.rb

"hello world"を出力するアプリケーションです。

$ cat app.rb
require 'sinatra'

get '/' do
  @text = "hello world\n"
  erb :index
end

views/index.erb

テンプレート

$ cat views/index.erb 
<!DOCTYPE html>
<html>
<body>
<%= @text %>
</body>
</html>

config.ru

config.ruファイルもつくります。

$ cat config.ru
require './app'
run Sinatra::Application

bundle install

依存モジュールのインストール

$ bundle install --path vendor/bundle

.gitignoreの用意

vendor、.bundleディレクトリを対象外とします

cat .gitignore
vendor
.bundle

手元で起動

$ bundle exec rackup -s Rhebok config.ru
Rhebok starts Listening on localhost:9292 Pid:77840

9292ポートで起動するのでブラウザやcurlで確認します。

Procfile

Rhebokでアプリケーションが起動するようにProcfileを書きます

$ cat Procfile
web: bundle exec rackup --port $PORT -s Rhebok -O OobGC=yes config.ru

OobGCを有効にしてみました。デフォルトで5個のworkerが起動します。

herokuへpush

git commitしてherokuへpushします

$ git init
$ git add .
$ git commit -m '…'
$ heroku create APP_NAME
$ git push heroku master

これでアプリケーションがherokuにて起動します。

curlでアクセスして確認します。

$ curl -v https://APP_NAME.herokuapp.com/
...
< HTTP/1.1 200 OK
< Connection: keep-alive
< Server: Rhebok
< Content-Type: text/html;charset=utf-8
< Content-Length: 59
< X-Xss-Protection: 1; mode=block
< X-Content-Type-Options: nosniff
< X-Frame-Options: SAMEORIGIN
< Date: Thu, 25 Dec 2014 02:47:58 GMT
< Via: 1.1 vegur
< 
<!DOCTYPE html>
<html>
<body>
hello world
</body>
</html>

Server: Rhebok と表示されたので、無事にRhebokにてアプリケーションが起動したことが確認できました。

同じアクセス数を処理している場合、RhebokはUnicornと比べてCPU使用率が低いという特徴もあるので、ぜひ試してくださいませ