Mac + unicorn + nginx + Rails 

環境

  • Mac OSX 10.8.3
  • Rails 3.2.13
  • Ruby 2.0.0-p0
  • Homebew

は導入済みとする

Unicorn

Install

gem install unicorn

設定

/config/unicorn.rb
を作成

# ワーカーの数
worker_processes 2

# ソケット経由で通信する
listen File.expand_path('tmp/sockets/unicorn.sock', ENV['RAILS_ROOT'])

# ログ
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

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
      # SIGTTOU だと worker_processes が多いときおかしい気がする
      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

起動

unicorn_rails -c config/unicorn.rb

その他オプション
-D デーモン化
-p ポート番号指定
-E RAILS_ENV指定

停止

Ctrl C

nginx

Install

brew install nginx

nginxへPathを通す
/usr/local/sbin/

設定ファイル

/usr/local/etc/nginx/nginx.conf
変更した所だけ記述

   upstream unicorn.rails_app{
  #自分のRailsアプリへの場所
        server unix:/Users/giwa/workspace/ror/depot/tmp/sockets/unicorn.sock fail_timeout=0;                                                                    
    } 
 
   server{
        location / {
            alias /Users/giwa/workspace/ror/depot/public;
            index  index.html index.htm index;

            try_files $uri/index.html $uri.html $uri @unicorn_rails_app;
        }

        location @unicorn_rails_app {
            proxy_redirect off;
            proxy_set_header Host               $host;
            proxy_set_header X-Real-IP          $remote_addr;
            proxy_set_header X-Forwarded-Host   $host;
            proxy_set_header X-Forwarded-Server $host;
            proxy_set_header X-Forwarded-For    $proxy_add_x_forwarded_for;
            proxy_pass http://unicorn.rails_app;
        }

      }

neginx -t でsyntaxが正しいかチェック