LoginSignup
1
2

More than 5 years have passed since last update.

Railsでunicornを使う

Posted at

Railsのデフォルトはpumaだが、unicornを使う必要性が出てきたのでアプリケーション・サーバーを変更したときのメモ。

環境

Rails 5.1.6
Ruby 2.3.6

手順

Gemfileに記載

gem 'unicorn'

unicorn.rbの設定

config/unicorn.rb
app_path = "/app" # アプリケーションに合わせて変更

case ENV['RAILS_ENV']
when 'production'
  worker_processes Integer(ENV["WEB_CONCURRENCY"] || 4) # ワーカー数の設定
else
  worker_processes 2
end

listen "/tmp/unicorn.sock", backlog: Integer(ENV["UNICORN_BACKLOG"] || 64) # バックログ数(裏で持っておくタスク)の設定

working_directory app_path

listen 8080 # unicorn用のポート

pid "#{app_path}/run/unicorn.pid" # このディレクトリを予め用意しておく

stderr_path "#{app_path}/log/unicorn.stderr.log"
stdout_path "#{app_path}/log/unicorn.stdout.log"

preload_app true

# use correct Gemfile on restarts
before_exec do |server|
  ENV['BUNDLE_GEMFILE'] = "#{app_path}/Gemfile"
end

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

pidファイルの置き場所を用意

今回はapp/run/配下にpidファイルを置く設定にしているので。app/run/.keepを作って保持しておく。

1
2
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
1
2