Skip to content

Instantly share code, notes, and snippets.

@willywos
Created October 9, 2012 01:44
Show Gist options
  • Save willywos/3856092 to your computer and use it in GitHub Desktop.
Save willywos/3856092 to your computer and use it in GitHub Desktop.
unicorn.rb
# 2 workers and 1 master
worker_processes 2
# Load the app into the master before forking workers for fast worker spawn times
preload_app true
# Restart any workers that haven't responded in 30 seconds
timeout 30
pid "/tmp/unicorn.my_site.pid"
# Listen on a Unix data socket
listen "/var/www/sample_rails_app/current/tmp/sockets/unicorn.sock", :backlog => 2048
stderr_path "/var/www/sample_rails_app/current/log/unicorn.stderr.log"
stdout_path "/var/www/sample_rails_app/current/log/unicorn.stdout.log"
before_fork do |server, worker|
# When sent a USR2, Unicorn will suffix its pidfile with .oldbin and
# immediately start loading up a new version of itself (loaded with a new
# version of our app). When this new Unicorn is completely loaded
# it will begin spawning workers. The first worker spawned will check to
# see if an .oldbin pidfile exists. If so, this means we've just booted up
# a new Unicorn and need to tell the old one that it can now die. To do so
# we send it a QUIT.
#
# Using this method we get 0 downtime deploys.
old_pid = '/tmp/unicorn.my_site.pid.oldbin'
if File.exists?(old_pid) && server.pid != old_pid
begin
Process.kill("QUIT", File.read(old_pid).to_i)
rescue Errno::ENOENT, Errno::ESRCH
# someone else did our job for us
end
end
end
before_exec do |server|
# BUNDLE_GEMFILE is currently set to the explicit revision directory,
# changing to the current directory so that we can do more deploys
# after the original revision directory has been cycled out
ENV['BUNDLE_GEMFILE'] = "/var/www/sample_rails_app/current/Gemfile"
end
after_fork do |server, worker|
# Unicorn master loads the app then forks off workers - because of the way
# Unix forking works, we need to make sure we aren't using any of the parent's
# sockets, e.g. db connection
if defined?(ActiveRecord::Base)
ActiveRecord::Base.establish_connection
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment