Random thoughts on programming and related topics.

Deploying With Sinatra + Capistrano + Unicorn

Today we’ll be deploying a simple Sinatra app with Capistrano, using Unicorn as our web server. First things first: let’s think of a stupid name for this project. What about “sincapun”? Any objections? Good, let’s proceed.

# define paths and filenamesdeploy_to="/srv/sincapun"rails_root="#{deploy_to}/current"pid_file="#{deploy_to}/shared/pids/unicorn.pid"socket_file="#{deploy_to}/shared/unicorn.sock"log_file="#{rails_root}/log/unicorn.log"err_log="#{rails_root}/log/unicorn_error.log"old_pid=pid_file+'.oldbin'timeout30worker_processes2# increase or decreaselistensocket_file,:backlog=>1024pidpid_filestderr_patherr_logstdout_pathlog_file# make forks fasterpreload_apptrue# make sure that Bundler finds the Gemfilebefore_execdo|server|ENV['BUNDLE_GEMFILE']=File.expand_path('../Gemfile',File.dirname(__FILE__))endbefore_forkdo|server,worker|defined?(ActiveRecord::Base)andActiveRecord::Base.connection.disconnect!# zero downtime deploy magic:# if unicorn is already running, ask it to start a new process and quit.ifFile.exists?(old_pid)&&server.pid!=old_pidbeginProcess.kill("QUIT",File.read(old_pid).to_i)rescueErrno::ENOENT,Errno::ESRCH# someone else did our job for usendendendafter_forkdo|server,worker|# re-establish activerecord connections.defined?(ActiveRecord::Base)andActiveRecord::Base.establish_connectionend

That should do it. Now you can deploy your app, assuming that you have RVM on the server, you can SSH into it and write to /srv directory.

12

cap deploy:setup
cap deploy

Deploy should spit a lot of text into the console, and there should be no errors. Verify that our unicorns are launched correctly by logging into the server and running this: