LoginSignup
53
54

More than 5 years have passed since last update.

rails4 + unicorn + nginx

Last updated at Posted at 2014-12-02

rails

基本的にはhttp://qiita.com/a_ishidaaa/items/74de8bdaecd637063c40 と同様に、production環境を準備する。一点、config/enviroments/production.rbのアセットの提供設定はfalseにする。nginxがやってくれる。

config/enviroments/production.rb
# Disable Rails's static asset server (Apache or nginx will already do this).
  config.serve_static_assets = false  

unicorn

インストール

Gemfileにunicornを追記

Gemfile

gem 'unicorn'

bundle install を実施

$bundle install

設定ファイル作成

config/unicorn.rbに設定を追記

config/unicorn.rb

@app_path = '/home/rails/rails/test/json_server'

worker_processes 2
working_directory "#{@app_path}/"
preload_app true
timeout 30
listen "/tmp/unicorn.sock", :backlog => 64
pid "/tmp/unicorn.pid"
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プロセス起動

$JSON_SERVER_DATABASE_PASSWORD=password bundle exec unicorn_rails -c config/unicorn.rb -E production -D

nginx

インストール

sudo yum install nginx

設定ファイル作成

/etc/nginx/conf.d/myapp.confにnginx用のコンフィグ追記

etc/nginx/conf.d/myapp.conf

upstream unicorn_server {
    # This is the socket we configured in unicorn.rb
    server unix:/tmp/unicorn.sock
    fail_timeout=0;
}

server {
    listen 80;
    client_max_body_size 4G;
    server_name _;

    keepalive_timeout 5;

    root /home/rails/rails/test/json_server/public;

    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;

        # If you don't find the filename in the static files
        # Then request it from the unicorn server
        if (!-f $request_filename) {
            proxy_pass http://unicorn_server;
            break;
        }
    }

    error_page 500 502 503 504 /500.html;
    location = /500.html {
        root /home/rails/rails/test/json_server/public;
    }
}


nginxの起動

$sudo /etc/rc.d/init.d/nginx start

53
54
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
53
54