kikeda1104's blog

備忘録・技術に関することを書いています。(webエンジニア)

unicornの利用

記録しておきたいネタが増えてきたkikeda1104です。
次やるときに、思い出すキーワードになるので、ぜひ記述しておきたい。
間に合うか....φ(・ω・` )

では、RailsのAppサーバとして、gem unicornを利用したいと思います。
次回は、nginxとの連携について書きたいと思います。

unicornの設定

Rails appの作成

$ rails new rails_app
$ cd rails_app

Gemfileへの追加

$ vim Gemfile
# Gemfile
gem 'unicorn'
$ bundle install

unicornの設定ファイルを作成

$ vim config/unicorn.rb
# config/unicorn.rb
@app_path = '/rails_app'

worker_processes 2
working_directory "#{@app_path}/"

# This loads the application in the master process before forking
# worker processes
# Read more about it here:
# http://unicorn.bogomips.org/Unicorn/Configurator.html
preload_app true

timeout 30

# This is where we specify the socket.
# We will point the upstream Nginx module to this socket later on
listen "/tmp/unicorn.sock", :backlog => 64

pid "/tmp/unicorn.pid"

# Set the path of the log files inside the log folder of the testapp
stderr_path "#{@app_path}/log/unicorn.stderr.log"
stdout_path "#{@app_path}/log/unicorn.stdout.log"

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

  old_pid = "#{server.config[:pid]}.oldbin"
  if old_pid != server.pid
    begin
      sig = (worker.nr + 1) >= server.worker_processes ? :QUIT : :TTOU
      Process.kill(sig, File.read(old_pid).to_i)
    rescue Errno::ENOENT, Errno::ESRCH
    end
  end

  sleep 1
end

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

上記の内容で保存します。

unicornを起動

$ bundle exec unicorn -E development -c config/unicorn.rb

参考

Vagrant(CentOS6.5)にRails4.1 + Nginx + Unicorn + MySQL環境でRailsを起動する。 - Qiita

Nginx + UnicornでRailsアプリ(Redmine)を動作させる | EasyRamble

以上です。