Lighting fast, zero-downtime deployments with git, capistrano, nginx and Unicorn
Everyone who has ever developed a web app has had to deploy it. Back in the day you simply uploaded your files with FTP and everything would be good. Today we have to clone git repositories, restart servers, set permissions, create symlinks to our configuration files, clean out caches and what not.
Doctor, what’s wrong?
In my opinion there are two critical problems with deployments today:
- They are slow
- They cause downtime
Both topics have been discussed by the likes of Twitter and Github. They have optimized their deployment process to allow for fast and continuous deployments. But, you are probably stuck with a default Capistrano install. As it turns out, with a little work, it’s quite easy to setup the same deployment process as Github and Twitter use.
For Ariejan.net, I’ve managed to get zero-downtime deployments that run in under 10 seconds. Yes, you read that right. ~
Let’s go!
This guide will help you setup your server and Rails 3.1 project for fast, zero-downtime deployments. I’ll be using Nginx+Unicorn to serve the application, git+capistrano for fast deployments. ~
The shopping list
Here’s a list of ingredients you’ll need:
- A recent Ubuntu server (I used 11.04 Netty)
- Your Rails 3.1 app
- A remote git repository that contains your app
Assumptions
I’m making some assumptions about your app:
- Ruby 1.9.2
- Rails 3.1 app using Postgres named
my_site
- You want to use RVM and Bundler
Setting up your server
There are a few things you need to setup before diving in. The first bit is run under the root
user.
Here’s the full apt-get
command list I used.
1apt-get update
2apt-get upgrade -y
3apt-get install build-essential ruby-full libmagickcore-dev imagemagick libxml2-dev \
4 libxslt1-dev git-core postgresql postgresql-client postgresql-server-dev-8.4 nginx curl
5apt-get build-dep ruby1.9.1
You’ll also need a separate user account to run your app. Believe me, you don’t want to run your app as root
. I call my user deployer
:
1useradd -m -g staff -s /bin/bash deployer
2passwd deployer
To allow deployer
to execute commands with super-user privileges, add the following to /etc/sudoers
. This required deployer
to enter his password before allowing super-user access.
1# /etc/sudoers
2%staff ALL=(ALL) ALL
Ruby and RVM
With that done, you’re ready to install rvm
, I performed a system-wide install, so make sure you run this as root.
1bash < <(curl -s https://rvm.beginrescueend.com/install/rvm)
Next up install the required ruby, in this case ruby-1.9.2-p290 and rubygems:
1rvm install ruby-1.9.2-p290
2wget http://production.cf.rubygems.org/rubygems/rubygems-1.8.10.tgz
3tar zxvf rubygems-1.8.10.tgz
4cd rubygems-1.8.10
5ruby setup.rb
Create a ~/.gemrc
file, this sets some sane defaults for your production server:
1# ~/.gemrc
2---
3:verbose: true
4:bulk_threshold: 1000
5install: --no-ri --no-rdoc --env-shebang
6:sources:
7- http://gemcutter.org
8- http://gems.rubyforge.org/
9- http://gems.github.com
10:benchmark: false
11:backtrace: false
12update: --no-ri --no-rdoc --env-shebang
13:update_sources: true
Also create this ~/.rvmrc
file to auto-trust your .rvmrc project files:
1# ~/.rvmrc
2rvm_trust_rvmrcs_flag=1
Note: do this for both root
and the deployer
user to avoid confusion later on.
Because you’ll be running your app in production-mode all the time, add the following line to /etc/environment
so you don’t have to repeat it with every Rails related command you use:
1RAILS_ENV=production
Postgres
I know not everybody uses Postgres, but I do. I love it and it beats the living crap out of MySQL. If you use MySQL, you’ll know what to do. Here are instructions for setting up Postgres. First create the database and login as the postgres
user:
1sudo -u postgres createdb my_site
2sudo -u postgres psql
Then execute the following SQL:
1CREATE USER my_site WITH PASSWORD 'password';
2GRANT ALL PRIVILEGES ON DATABASE my_site TO my_site;
Nginx
Nginx is a great piece of Russian engineering. You’ll need some configuration though:
1# /etc/nginx/sites-available/default
2upstream my_site {
3 # fail_timeout=0 means we always retry an upstream even if it failed
4 # to return a good HTTP response (in case the Unicorn master nukes a
5 # single worker for timing out).
6
7 # for UNIX domain socket setups:
8 server unix:/tmp/my_site.socket fail_timeout=0;
9}
10
11server {
12 # if you're running multiple servers, instead of "default" you should
13 # put your main domain name here
14 listen 80 default;
15
16 # you could put a list of other domain names this application answers
17 server_name my_site.example.com;
18
19 root /home/deployer/apps/my_site/current/public;
20 access_log /var/log/nginx/my_site_access.log;
21 rewrite_log on;
22
23 location / {
24 #all requests are sent to the UNIX socket
25 proxy_pass http://my_site;
26 proxy_redirect off;
27
28 proxy_set_header Host $host;
29 proxy_set_header X-Real-IP $remote_addr;
30 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
31
32 client_max_body_size 10m;
33 client_body_buffer_size 128k;
34
35 proxy_connect_timeout 90;
36 proxy_send_timeout 90;
37 proxy_read_timeout 90;
38
39 proxy_buffer_size 4k;
40 proxy_buffers 4 32k;
41 proxy_busy_buffers_size 64k;
42 proxy_temp_file_write_size 64k;
43 }
44
45 # if the request is for a static resource, nginx should serve it directly
46 # and add a far future expires header to it, making the browser
47 # cache the resource and navigate faster over the website
48 # this probably needs some work with Rails 3.1's asset pipe_line
49 location ~ ^/(images|javascripts|stylesheets|system)/ {
50 root /home/deployer/apps/my_site/current/public;
51 expires max;
52 break;
53 }
54}
All dandy! One more then:
1# /etc/nginx/nginx.conf
2user deployer staff;
3
4# Change this depending on your hardware
5worker_processes 4;
6pid /var/run/nginx.pid;
7
8events {
9 worker_connections 1024;
10 multi_accept on;
11}
12
13http {
14 sendfile on;
15 tcp_nopush on;
16 tcp_nodelay off;
17 # server_tokens off;
18
19 # server_names_hash_bucket_size 64;
20 # server_name_in_redirect off;
21
22 include /etc/nginx/mime.types;
23 default_type application/octet-stream;
24
25 access_log /var/log/nginx/access.log;
26 error_log /var/log/nginx/error.log;
27
28 gzip on;
29 gzip_disable "msie6";
30
31 # gzip_vary on;
32 gzip_proxied any;
33 gzip_min_length 500;
34 # gzip_comp_level 6;
35 # gzip_buffers 16 8k;
36 # gzip_http_version 1.1;
37 gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
38
39 ##
40 # Virtual Host Configs
41 ##
42
43 include /etc/nginx/conf.d/*.conf;
44 include /etc/nginx/sites-enabled/*;
45}
Okay, that’s Nginx for you. You should start it now, although you’ll get a 500 or proxy error now:
1/etc/init.d/nginx start
Unicorn
The next part involves setting up Capistrano and unicorn for your project. This is where the real magic will happen.
You’ll be doing cap deploy
99% of the time. This command needs to be fast. To accomplish this I want to utilize the power of git. Instead of having Capistrano juggle around a bunch of release directories, which is painfully slow, I want to use git to switch to the correct version of my app. This means I’ll have just one directory that is updated by git when it needs to be.
Let’s get started by adding some gems to your app. When done run bundle install
.
1 # Gemfile
2 gem "unicorn"
3
4 group :development do
5 gem "capistrano"
6 end
The next step is adding a configuration file for Unicorn in config/unicorn.rb
:
1# config/unicorn.rb
2# Set environment to development unless something else is specified
3env = ENV["RAILS_ENV"] || "development"
4
5# See http://unicorn.bogomips.org/Unicorn/Configurator.html for complete
6# documentation.
7worker_processes 4
8
9# listen on both a Unix domain socket and a TCP port,
10# we use a shorter backlog for quicker failover when busy
11listen "/tmp/my_site.socket", :backlog => 64
12
13# Preload our app for more speed
14preload_app true
15
16# nuke workers after 30 seconds instead of 60 seconds (the default)
17timeout 30
18
19pid "/tmp/unicorn.my_site.pid"
20
21# Production specific settings
22if env == "production"
23 # Help ensure your application will always spawn in the symlinked
24 # "current" directory that Capistrano sets up.
25 working_directory "/home/deployer/apps/my_site/current"
26
27 # feel free to point this anywhere accessible on the filesystem
28 user 'deployer', 'staff'
29 shared_path = "/home/deployer/apps/my_site/shared"
30
31 stderr_path "#{shared_path}/log/unicorn.stderr.log"
32 stdout_path "#{shared_path}/log/unicorn.stdout.log"
33end
34
35before_fork do |server, worker|
36 # the following is highly recomended for Rails + "preload_app true"
37 # as there's no need for the master process to hold a connection
38 if defined?(ActiveRecord::Base)
39 ActiveRecord::Base.connection.disconnect!
40 end
41
42 # Before forking, kill the master process that belongs to the .oldbin PID.
43 # This enables 0 downtime deploys.
44 old_pid = "/tmp/unicorn.my_site.pid.oldbin"
45 if File.exists?(old_pid) && server.pid != old_pid
46 begin
47 Process.kill("QUIT", File.read(old_pid).to_i)
48 rescue Errno::ENOENT, Errno::ESRCH
49 # someone else did our job for us
50 end
51 end
52end
53
54after_fork do |server, worker|
55 # the following is *required* for Rails + "preload_app true",
56 if defined?(ActiveRecord::Base)
57 ActiveRecord::Base.establish_connection
58 end
59
60 # if preload_app is true, then you may also want to check and
61 # restart any other shared sockets/descriptors such as Memcached,
62 # and Redis. TokyoCabinet file handles are safe to reuse
63 # between any number of forked children (assuming your kernel
64 # correctly implements pread()/pwrite() system calls)
65end
Okay, as you can see there’s some nice stuff in there to accomplish zero-downtime restarts. Let me tell you a bit more about that.
Unicorn starts as a master
process and then spawns several workers (we configured four). When you send Unicorn the ‘USR2’ signal it will rename itself to master (old)
and create a new master process. The old master will keep running.
Now, when the new master starts and forks a worker it checks the PID files of the new and old Unicorn masters. If those are different, the new master was started correctly. We can now send the old master the QUIT signal, shutting it down gracefully (e.g. let it handle open requests, but not new ones).
All the while, you have restarted your app, without taking it down: zero downtime!
Capistrano
Now for Capistrano, add the following to your Gemfile
.
1# Gemfile
2group :development do
3 gem "capistrano"
4end
And generate the necessary Capistrano files.
1capify .
Open up config/deploy.rb
and replace it with the following.
This deploy script does all the usual, but the special part is where you reset the release paths to the current path, making the whole release directory unnecessary.
Also not that the update_code
is overwritten to do a simple git fetch
and git reset
- this is very fast indeed!
1# config/deploy.rb
2require "bundler/capistrano"
3
4set :scm, :git
5set :repository, "git@codeplane.com:you/my_site.git"
6set :branch, "origin/master"
7set :migrate_target, :current
8set :ssh_options, { :forward_agent => true }
9set :rails_env, "production"
10set :deploy_to, "/home/deployer/apps/my_site"
11set :normalize_asset_timestamps, false
12
13set :user, "deployer"
14set :group, "staff"
15set :use_sudo, false
16
17role :web, "123.456.789.012"
18role :app, "123.456.789.012"
19role :db, "123.456.789.012", :primary => true
20
21set(:latest_release) { fetch(:current_path) }
22set(:release_path) { fetch(:current_path) }
23set(:current_release) { fetch(:current_path) }
24
25set(:current_revision) { capture("cd #{current_path}; git rev-parse --short HEAD").strip }
26set(:latest_revision) { capture("cd #{current_path}; git rev-parse --short HEAD").strip }
27set(:previous_revision) { capture("cd #{current_path}; git rev-parse --short HEAD@{1}").strip }
28
29default_environment["RAILS_ENV"] = 'production'
30
31# Use our ruby-1.9.2-p290@my_site gemset
32default_environment["PATH"] = "--"
33default_environment["GEM_HOME"] = "--"
34default_environment["GEM_PATH"] = "--"
35default_environment["RUBY_VERSION"] = "ruby-1.9.2-p290"
36
37default_run_options[:shell] = 'bash'
38
39namespace :deploy do
40 desc "Deploy your application"
41 task :default do
42 update
43 restart
44 end
45
46 desc "Setup your git-based deployment app"
47 task :setup, :except => { :no_release => true } do
48 dirs = [deploy_to, shared_path]
49 dirs += shared_children.map { |d| File.join(shared_path, d) }
50 run "#{try_sudo} mkdir -p #{dirs.join(' ')} && #{try_sudo} chmod g+w #{dirs.join(' ')}"
51 run "git clone #{repository} #{current_path}"
52 end
53
54 task :cold do
55 update
56 migrate
57 end
58
59 task :update do
60 transaction do
61 update_code
62 end
63 end
64
65 desc "Update the deployed code."
66 task :update_code, :except => { :no_release => true } do
67 run "cd #{current_path}; git fetch origin; git reset --hard #{branch}"
68 finalize_update
69 end
70
71 desc "Update the database (overwritten to avoid symlink)"
72 task :migrations do
73 transaction do
74 update_code
75 end
76 migrate
77 restart
78 end
79
80 task :finalize_update, :except => { :no_release => true } do
81 run "chmod -R g+w #{latest_release}" if fetch(:group_writable, true)
82
83 # mkdir -p is making sure that the directories are there for some SCM's that don't
84 # save empty folders
85 run <<-CMD
86 rm -rf #{latest_release}/log #{latest_release}/public/system #{latest_release}/tmp/pids &&
87 mkdir -p #{latest_release}/public &&
88 mkdir -p #{latest_release}/tmp &&
89 ln -s #{shared_path}/log #{latest_release}/log &&
90 ln -s #{shared_path}/system #{latest_release}/public/system &&
91 ln -s #{shared_path}/pids #{latest_release}/tmp/pids &&
92 ln -sf #{shared_path}/database.yml #{latest_release}/config/database.yml
93 CMD
94
95 if fetch(:normalize_asset_timestamps, true)
96 stamp = Time.now.utc.strftime("%Y%m%d%H%M.%S")
97 asset_paths = fetch(:public_children, %w(images stylesheets javascripts)).map { |p| "#{latest_release}/public/#{p}" }.join(" ")
98 run "find #{asset_paths} -exec touch -t #{stamp} {} ';'; true", :env => { "TZ" => "UTC" }
99 end
100 end
101
102 desc "Zero-downtime restart of Unicorn"
103 task :restart, :except => { :no_release => true } do
104 run "kill -s USR2 `cat /tmp/unicorn.my_site.pid`"
105 end
106
107 desc "Start unicorn"
108 task :start, :except => { :no_release => true } do
109 run "cd #{current_path} ; bundle exec unicorn_rails -c config/unicorn.rb -D"
110 end
111
112 desc "Stop unicorn"
113 task :stop, :except => { :no_release => true } do
114 run "kill -s QUIT `cat /tmp/unicorn.my_site.pid`"
115 end
116
117 namespace :rollback do
118 desc "Moves the repo back to the previous version of HEAD"
119 task :repo, :except => { :no_release => true } do
120 set :branch, "HEAD@{1}"
121 deploy.default
122 end
123
124 desc "Rewrite reflog so HEAD@{1} will continue to point to at the next previous release."
125 task :cleanup, :except => { :no_release => true } do
126 run "cd #{current_path}; git reflog delete --rewrite HEAD@{1}; git reflog delete --rewrite HEAD@{1}"
127 end
128
129 desc "Rolls back to the previously deployed version."
130 task :default do
131 rollback.repo
132 rollback.cleanup
133 end
134 end
135end
136
137def run_rake(cmd)
138 run "cd #{current_path}; #{rake} #{cmd}"
139end
Now there is one little thing you’ll need to do. I like to run my apps, even on the server, to use their own gemset. This keeps everything clean and isolated. Login to the deployer
account and create your gemset. Next run rvm info
and fill the PATH
, GEM_HOME
and GEM_PATH
variables accordingly.
Don’t forget to install
bundler
in your new gemset
Database configuration
I always like to keep the database configuration out of git. I’ll place it in the shared directory.
1# /home/deployer/apps/my_site/shared/database.yml
2production:
3 adapter: postgresql
4 encoding: unicode
5 database: my_site_production
6 pool: 5
7 username: my_site
8 password: password
First setup
Now setup your deployment like this:
1cap deploy:setup
This will clone your repo and link your database.yml
file. Optionally, you may want to run migrations or upload an SQL dump to get started quickly with your app.
Deployments
Whenever you have a new feature developed in a feature branch, this is the process of deploying it:
- Merge
feature_branch
intomaster
- Run your tests to make sure everything is dandy.
- Push
master
- Run
cap deploy
For Ariejan.net, step 4 takes less than 10 seconds. Unicorn is restarted with zero-downtime so users don’t even notice the site was updated.
What’s next?
You now have fast, zero-downtime deployments working for your app. There are still some things you should to (which I might cover in some later post):
- Tweak the nginx and Unicorn settings (especially number of workers); Perform some tests and see what works best for your app/server combination.
- Add caching to nginx (or add Varnish)
- Enable some monitoring, maybe Monit
- Crank up security a notch
- Integrate other deployment tasks like
whenever
or prepare your assets