unicornの起動とnginxとの接続memo

テスト用のアプリ作成

$rails new unicorndemo -d mysql
$cd unicorndemo

gemrcの設定

vim .gemrc
gem: --no-ri --no-rdoc

gemの設定&インストール

$vim Gemfile
----------------------
gem 'unicorn'
----------------------
$bundle install --path vendor/bundler

MySQLの準備

bundle exec rake db:create
bundle exec rake db:migrate

unicorn.rbの作成

vim config/unicorn.rb
=============================================================
# -*- coding: utf-8 -*-
# ワーカーの数
worker_processes 2

# ソケット
listen  '/tmp/unicorn.sock'
pid     '/tmp/unicorn.pid'

# ログ
log = '${my_app}/log/unicorn.log'
stderr_path File.expand_path('log/unicorn.log', ENV['RAILS_ROOT'])
stdout_path File.expand_path('log/unicorn.log', ENV['RAILS_ROOT'])

preload_app true
GC.respond_to?(:copy_on_write_friendly=) and GC.copy_on_write_friendly = true

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
   sig = (worker.nr + 1) >= server.worker_processes ? :QUIT : :TTOU
   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 -c config/unicorn.rb -p 3000 -E development -D

起動確認

ps -ef | grep unicorn | grep -v grep

unicornの停止

cat /tmp/unicorn.pid
kill -QUIT <pid(tmp/unicorn.pidに記載されてるPID)>