LoginSignup
29
28

More than 5 years have passed since last update.

Unicorn with Rails on Heroku (Cedar stack)

Last updated at Posted at 2012-09-06

という訳でUnicornにしてみました。

以下「取り敢えず動く」セットアップ手順です。
実質
How to get 4x the performance out of Heroku with Unicorn
の中途半端な和訳です。

-

Install

$ gem install unicorn

Gemfile
gem 'unicorn'

Procfileを作ります。
$ vim Procfile

Procfile
web: bundle exec unicorn -p $PORT -c ./config/unicorn.rb

config/unicorn.rbを作ります。
$ vim confing/unicorn.rb

config/unicorn.rb
worker_processes 3
timeout 30
preload_app true

before_fork do |server, worker|
  # Replace with MongoDB or whatever
  if defined?(ActiveRecord::Base)
    ActiveRecord::Base.connection.disconnect!
    Rails.logger.info('Disconnected from ActiveRecord')
  end

  # If you are using Redis but not Resque, change this
  if defined?(Resque)
    Resque.redis.quit
    Rails.logger.info('Disconnected from Redis')
  end

  sleep 1
end

after_fork do |server, worker|
  # Replace with MongoDB or whatever
  if defined?(ActiveRecord::Base)
    ActiveRecord::Base.establish_connection
    Rails.logger.info('Connected to ActiveRecord')
  end

  # If you are using Redis but not Resque, change this
  if defined?(Resque)
    Resque.redis = ENV['REDIS_URI']
    Rails.logger.info('Connected to Redis')
  end
end

Loggingを有効にするため、application.rbに追記します。

config/application.rb
config.logger = Logger.new(STDOUT)

-

About Config

詳細なすべての設定パラメータはUnicorn Documentationで見つかります。

-
worker_processes: Unicorn workerの数を設定します。
timeout: 一つのworkerが反応を返さなくなってからリスタートまでの時間です
preload_app: forking workerの前にアプリケーションを読み込みます。NewRelicを使う場合はtrueに、設定しない場合はNewRelicで何のdataも見れません。
before_fork/after_fork: databaseにbofore_fork内で切断し、after_fork内で再接続します。これらのハンドラーなしではdatabase errorが発生します。

-

worker_processes数を変更する際はNewRelic等でメモリの使用状況を確認しながら行いましょう。
一つのDynoにつき512MBが許容範囲なので、それを超える設定をしてしまうとDynoが落ちます。(どこかで1.5GB超えると強制終了とか読んだ気がするがソースがない)
参考元にはDynosの数とworker_processes数を同じにしましょう、と書かれているのですが、その辺りは詳しく分かりません。
worker_processesは一つのDyno上で動くUnicorn workerの数なのに、Dynosの数と併せる理由って…?

参考元にworker数毎のベンチマーク結果など載ってますので、興味のある方は目を通すのも良いと思います。

試しにNewRelicで確認しながらworker_processesを2から4にしてみた所、綺麗にメモリ使用量が倍になりました。
無料範囲内で遊んでるだけなのでworker Dynoもいない状態でweb Dynoひとつなんですが、これって意味あるのかな。

-

etc.

設定に関しては
次世代RailsサーバーUnicornを使ってみた
nginx + Unicorn を試してみた
Unicorn: Rack HTTP server for fast clients and Unix
辺りを眺めながら
How to get 4x the performance out of Heroku with Unicorn
に従って行いました。上の3つはもう少し分かってから詳しく読んで参考にしようかと思います。

-

書き終わってから和訳してる部分と自分の言葉が中途半端に混ざってる部分があって申し訳ない気分になりました。どうせなら全部普通に訳せばよかった。

29
28
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
29
28