Skip to content

Instantly share code, notes, and snippets.

@markottaviani
Forked from rchampourlier/unicorn.rb
Created December 5, 2011 13:24
Show Gist options
  • Save markottaviani/1433575 to your computer and use it in GitHub Desktop.
Save markottaviani/1433575 to your computer and use it in GitHub Desktop.
Postgresql fixed template for unicorn.rb to use with Capistrano deployment recipe
# This file has been generated from unicorn_template.rb.erb which is greatly inspired from:
# https://github.com/ricodigo/ricodigo-capistrano-recipes/blob/master/generators/unicorn.rb.erb
#
# See http://unicorn.bogomips.org/Unicorn/Configurator.html for complete
# documentation.
# Local variables
old_pid = '<%= unicorn_pid + ".old" %>'
# Unicorn setup
worker_processes <%= unicorn_workers %>
timeout <%= unicorn_workers_timeout %>
# Listen on a Unix data socket
listen '<%= unicorn_socket %>', :backlog => 1024
pid '<%= unicorn_pid %>'
user '<%= unicorn_user %>', '<%= unicorn_group %>'
# Help ensure your application will always spawn in the symlinked
# "current" directory that Capistrano sets up.
working_directory '<%= "#{deploy_to}/current" %>'
stderr_path '<%= "#{logs_path}/unicorn.stderr.log" %>'
stdout_path '<%= "#{logs_path}/unicorn.stdout.log" %>'
preload_app true
before_fork do |server, worker|
# the following is highly recomended for Rails + "preload_app true"
# as there's no need for the master process to hold a connection
if defined?(ActiveRecord::Base)
ActiveRecord::Base.connection.disconnect!
end
# Before forking, kill the master process that belongs to the .oldbin PID.
# This enables 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
after_fork do |server, worker|
# the following is *required* for Rails + "preload_app true",
if defined?(ActiveRecord::Base)
ActiveRecord::Base.establish_connection
end
# if preload_app is true, then you may also want to check and
# restart any other shared sockets/descriptors such as Memcached,
# and Redis. TokyoCabinet file handles are safe to reuse
# between any number of forked children (assuming your kernel
# correctly implements pread()/pwrite() system calls)
end
@markottaviani
Copy link
Author

I was having problems with Postgresql getting confused about the different unicorn worker processes. Every few clicks on the website would generate a "prepared statement already exists" error. This forked config file seems to fix the problem for me. Each unicorn worker process will have its own connection to postgres.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment