unicornについて

unicornについてわかってなかったので、調べました。

ついでに設定ファイルを書いておきました。

間違っていたら教えてくださいm( )m

unicornとは

Rack webサーバーの一種です。

Rack webサーバーが何をしているかという、下記の問題を解決してくれています。

フレームワーク(rails)  ← Rack webサーバー → Apache NginxなどのWebサーバー

フレームワークとWebサーバーの中間を管理してくれているものです。

何でこれが必要なの?ということですが、いろんなフレームワークが出現する度に、Webサーバーと連携をする処理を書くのがめんどくさいということで、Rack webサーバーに対応するように書けば、あとはWebサーバーのやり取りを書かなくて良いという発想から生まれました。

Apacheに対応するための設定、Nginxに対応するための設定をいちいち書くのがやっとれないということです。

その一種がunicornです。

unicornの特徴として、unicorn workerを使用して、サーバーをダウンしなくてもデプロイできます。

実際はunicorn + nginxで設定するパターンがrailsだと多いと思います。

私がやろうとしているのも、同じパターンです。

設定ファイル

config/unicorn.rb

# Nginxで本番で動かす場合は設定が必要
listen 8080

# pid(Process ID) fileの位置を指定
pid 'tmp/pids/unicorn.pid'

# ワーカーの数を指定する
worker_processes 2

# リクエストのタイムアウトの秒数を指定する
timeout 15

# ダウンタイムをなくすため、アプリを事前に読み込む
preload_app true

# Unicornのログの出力先を指定する
ROOT = File.dirname(File.dirname(__FILE__))
stdout_path "#{ROOT}/log/unicorn_stdout.log"
stderr_path "#{ROOT}/log/unicorn_stderr.log"

before_fork do |server, worker|
  defined?(ActiveRecord::Base) and ActiveRecord::Base.connection.disconnect!

  old_pid = "#{ server.config[:pid] }.oldbin"
  unless old_pid == server.pid
    begin
      Process.kill :QUIT, File.read(old_pid).to_i
    rescue Errno::ENOENT, Errno::ESRCH
    end
  end
end

after_fork do |server, worker|
  defined?(ActiveRecord::Base) and ActiveRecord::Base.establish_connection
end

これでbundle exec unicorn_rails -c config/unicorn.rbをすれば、unicornが立ち上がります。

ps -ax | grep unicornで動いているかを確認します。

3766 ttys001    0:03.63 unicorn_rails master -c config/unicorn.rb
 3788 ttys001    0:00.00 unicorn_rails worker[0] -c config/unicorn.rb
 3789 ttys001    0:00.00 unicorn_rails worker[1] -c config/unicorn.rb

workerが2個動いているので、並列処理を行っていることがわかります。

あとはnginxをつなげて本番環境で動かし、capstranoをクリアするのがしんどいな・・・

インフラ弱いので、頑張る。

参考

fujiike.hateblo.jp

http://route477.net/d/?date=20080716

Rails unicorn · herokaijp/devcenter Wiki · GitHub