Skip to content
Create a gist now

Instantly share code, notes, and snippets.

Embed URL


Subversion checkout URL

You can clone with
Download ZIP
Unicorn config for use with bundler and capistrano - fixes issues with environment pollution.rb
# My pimped out unicorn config, with incremental killof
# and all the latest capistrano & bundler-proofing
# @jamiew ::
application = ""
environment = ENV['RACK_ENV'] || ENV['RAILS_ENV'] || 'production'
app_path = "/srv/#{application}"
bundle_path = "#{app_path}/shared/bundle"
timeout 30
preload_app true
worker_processes 8
# Listen on both fast-failing unix data socket & a backloggable TCP connection
listen "/srv/#{application}/shared/tmp/sockets/unicorn.sock", :backlog => 64
listen 8080, :backlog => 256
# Hard-set the CWD & pidfile to ensure app-reloading consistency
working_directory "#{app_path}/current"
stderr_path "#{app_path}/shared/log/unicorn.stderr.log"
pid "#{app_path}/shared/tmp/pids/"
# Helps ensure the correct unicorn binary is used when upgrading with USR2
# See
Unicorn::HttpServer::START_CTX[0] = "#{bundle_path}/bin/unicorn"
# REE-friendly
if GC.respond_to?(:copy_on_write_friendly=)
GC.copy_on_write_friendly = true
# Rails breaks unicorn's logger formatting, reset it
Unicorn::Configurator::DEFAULTS[:logger].formatter =
# Forcibly clean environment variables between bundlings
before_exec do |_|
paths = (ENV["PATH"] || "").split(File::PATH_SEPARATOR)
paths.unshift "#{bundle_path}/bin"
ENV["PATH"] = paths.uniq.join(File::PATH_SEPARATOR)
ENV["GEM_HOME"] = ENV['GEM_PATH'] = bundle_path
ENV["BUNDLE_GEMFILE"] = "/srv/#{application}/current/Gemfile"
before_fork do |server, worker|
ActiveRecord::Base.connection.disconnect! if defined?(ActiveRecord::Base)
# Kill the old master as soon as our 1st worker is ready
# old_pid = "/srv/#{application}/shared/tmp/pids/"
# if File.exists?(old_pid) && != old_pid
# begin
# Process.kill("QUIT",
# rescue Errno::ENOENT, Errno::ESRCH
# # someone else killed the old master already
# end
# end
# Incremental kill-off
old_pid = "#{server.config[:pid]}.oldbin"
if old_pid !=
sig = ( + 1) >= server.worker_processes ? :QUIT : :TTOU
puts "Sending #{sig} signal to old unicorn master..."
rescue Errno::ENOENT, Errno::ESRCH
# Throttle the master from forking too quickly (for incremental kill-off only)
sleep 1
after_fork do |server, worker|
ActiveRecord::Base.establish_connection if defined?(ActiveRecord::Base)

The money is at the bottom WHATUP


Why do you shutdown newrelic agent at the bottom in after_fork?


What is the effect of the environment = on top? It's not used elsewhere in the script and to my knowledge unicorn doesn't support declaring the environment in unicorn.rb


Why there's an underscore '_' in before_exec do line?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.