unicornの導入
unicornについて
mongrel、thinと同じRails用のHTTPサーバ。実際にはRackに対応したアプリケーションならなんでも動くらしい。
Twitterもmongrelからunicornに乗り換えたらしいので、この機会に使ってみる。 ちなみに、各サーバの印象はこんな感じ(2010/7/2時点)
サーバ | 運用のしやすさ | 速度 | メモリ使用量 |
Mongrel | 数が増えると面倒 | 普通 | 少ない |
Thin | 数が増えると面倒 | 早い | 少ない |
Passenger | かなり楽 | 遅い | かなり多い |
Unicorn | 数が増えると面倒になるが、それでもmongrelやthinよりは楽 | thinと同等か少し早い | thinやmongrelと同じ |
運用面ではPassengerが群を抜いて楽だし、速度面を考えるとMongrel、Thin、Unicornが有利。
メモリ使用量でいえば、Passengerはかなりメモリを食ってしまう。他の3つに関しては同じようなもの。
Unicornは1つのプロセスの中で複数のスレッドが動くので、mongrelやthinのように1つポートで1リクエストしか同時に扱えないという問題をクリアしている。
そのため、mongrelやthinを20個起動しなくてはいけない場合でも、unicornなら1つだけ起動して20プロセス動かすように設定すれば良い。
または2つ起動して、各プロセスが10個のスレッドを持つようにするなど。
このような違いがあるため、unicornは1つのプロセスで複数のRailsを動かすからメモリを食うように見えるが、
mongrelやthinを10個起動した場合と、unicornが1つのプロセスで10個のスレッドを持つ場合を比較すればおそらく同じくらいのメモリを使うと思う。
unicornの導入、設定
運用のイメージ
- RAILS_ROOTはここでは/home/rails/approotとする
- railsアプリの実行ユーザはrails
- Apache + proxy_balancer + unicornx2(ポートは3000と3001)
- unicornのワーカースレッドは5個(2x5=10個のRailsプロセスが動く)
- unicornの設定ファイルはRAILS_ROOT/config以下に置く
- /home/rails/approot/config/unicorn.conf
手順
- unicornのインストール
$ sudo gem install unicorn
- unicornの設定ファイル(config/unicorn.conf)
記法はRubyの文法が使える
# See http://unicorn.bogomips.org/Unicorn/Configurator.html for complete # See also http://unicorn.bogomips.org/examples/unicorn.conf.rb for rails_env = 'production' worker_processes 5 working_directory '/home/rails/approot' port = 3000 listen port, :tcp_nopush => true timeout 30 pid 'tmp/pids/unicorn.pid' preload_app true stderr_path 'log/unicorn.log' stdout_path 'log/unicorn.log' before_fork do |server, worker| # この設定はpreload_app trueの場合に必須 defined?(ActiveRecord::Base) and ActiveRecord::Base.connection.disconnect! end after_fork do |server, worker| # この設定はpreload_app trueの場合に必須 defined?(ActiveRecord::Base) and ActiveRecord::Base.establish_connection end
- VirtualHostの設定。 ここを参考にした、というそのまま。
設定が終わったらApacheを再起動する<VirutalHost *:80> ServerName www.example.com DocumentRoot /home/rails/approot/public CustomLog logs/access.log combined ErrorLog logs/error.log ProxyRequests Off <Proxy *> Order deny,allow Allow from all </Proxy> ProxyPass /images ! ProxyPass /stylesheets ! ProxyPass /javascripts ! ProxyPass /robots.txt ! ProxyPass /favicon.ico ! ProxyPass / http://localhost:3000/ ProxyPassReverse / http://localhost:3000/ </VirtualHost>
- unicornの起動
# su - rails $ cd approot $ unicorn_rails -D -c /home/rails/approot/config/unicorn.conf
- unicornの停止
停止するコマンドは無いので、PIDを指定してkill kill `cat /home/rails/approot/tmp/pids/unicorn.pid`
- unicornの再起動(kill -HUP PID)
kill -HUP `cat /home/rails/approot/tmp/pids/unicorn.pid`