Deploying a Rails App with Capistrano
Deploying a Rails app to a Vagrant VM and EC2 with Capistrano.
This post was originally published in Japanese on Qiita.
This is part 2 of 2. It deploys to the servers built in part 1, Provisioning Servers for Rails with Ansible.
What is Capistrano?
Capistrano is a deployment tool written in Ruby. You run cap on your local machine, and it connects to each server over SSH and runs a list of tasks there.
Goals
Deploy a Rails app from the local machine to the EC2 server built in part 1:
- Run the app with Unicorn behind the nginx that part 1 installed
- Restart Unicorn on every deploy without downtime
- Leave CI and automated deploys out of scope
Install Capistrano
Add Capistrano and its plugins to the app’s Gemfile, then run bundle install:
group :development do
gem 'capistrano', :require => false
gem 'capistrano-rails', :require => false
gem 'capistrano-rbenv', :require => false
gem 'capistrano-bundler', :require => false
gem 'capistrano3-unicorn', :require => false
end
capistrano is the core, and each plugin adds tasks for one tool: capistrano-rails for database migrations, capistrano-rbenv to run commands with the rbenv Ruby, capistrano-bundler for bundle install, and capistrano3-unicorn to start, stop and restart Unicorn. They’re only needed on the machine you deploy from, so they go in the development group. :require => false keeps Rails from loading them when the app boots; the Capfile loads them instead.
bundle exec cap install STAGES=development,production
mkdir -p config/deploy
create config/deploy.rb
create config/deploy/development.rb
create config/deploy/production.rb
mkdir -p lib/capistrano/tasks
Capified
cap install generates the Capistrano skeleton. STAGES=development,production sets the stage names: you get one file per stage under config/deploy/, and the stage name is the first argument of every later cap command (cap development ..., cap production ...). config/deploy.rb holds settings shared by every stage, and each stage file says which server to deploy to and how to log in.
These are the files in the app that this post touches:
my_app/
├── Capfile
├── Gemfile
└── config/
├── deploy.rb
├── deploy/
│ ├── development.rb
│ └── production.rb
└── unicorn.rb
Deploy settings
set :application, 'my_app'
set :repo_url, 'git@github.com:foobar/my_app.git'
set :deploy_to, '/var/www/my_app'
set :log_level, :info
set :linked_dirs, %w{bin log tmp/pids tmp/cache tmp/sockets vendor/bundle public/system}
set :bundle_flags, "--deployment --quiet"
after 'deploy:publishing', 'deploy:restart'
namespace :deploy do
task :restart do
invoke 'unicorn:restart'
end
end
application: the app’s name. Capistrano uses it in a few paths, such as its temporary directory/tmp/my_app/on the server.repo_url: the Git repository to deploy. The server downloads the code from here, so it needs access to the repository (seeforward_agentbelow).deploy_to: where the app lives on the server. This is the default path, but I wrote it out because nginx and Unicorn use the same path.log_level: how muchcapprints. The default,:debug, also prints the output of every command, which is a lot.linked_dirs: folders that every release shares throughshared/, so logs, PID files and installed gems aren’t lost on each deploy.
The last block restarts Unicorn after each deploy, because Capistrano 3 doesn’t do that on its own. It comes straight from the capistrano3-unicorn README.
How Capistrano lays out the server
Every deploy gets its own directory on the server:
/var/www/my_app/
├── current -> /var/www/my_app/releases/20141003083242
├── releases/
│ └── 20141003083242/
├── repo/
└── shared/
current is a symlink to the release being served. Capistrano switches it only after the new release is in place, and cap production deploy:rollback points it back at the previous release. By default the last five releases are kept and older ones are deleted. repo/ is a mirror of the Git repository, and shared/ holds files that every release uses, such as logs.
Which server to deploy to
Each stage file names the server to deploy to, the user Capistrano logs in as, and the server’s roles. This is the one for EC2:
server '54.xxx.xxx.xxx',
user: 'ec2-user',
roles: %w{app},
ssh_options: {
keys: [File.expand_path('~/.ssh/aws.pem')],
forward_agent: true,
auth_methods: %w(publickey) # never fall back to a password prompt
}
The address, user and key are the same ones in part 1’s Ansible inventory. Roles decide which tasks run on which server; capistrano3-unicorn runs its tasks on servers with the app role. The dev VM’s stage file is in the appendix.
The servers have no key for GitHub, so on their own they can’t fetch the code from the repository. forward_agent: true turns on SSH agent forwarding: while Capistrano is connected, the server can use the keys in the SSH agent on your local machine, so git on the server logs in to GitHub with your key. Your GitHub key has to be loaded in the local agent; ssh-add -l lists the keys it holds.
Unicorn
Unicorn is the app server that runs Rails. Its config, config/unicorn.rb, follows the example config from capistrano3-unicorn, so Unicorn can restart on new code without downtime. The full file is in the appendix. Its paths point at current/, so Unicorn always runs the release Capistrano published last, and listen opens the socket that part 1’s nginx config sends requests to (the upstream app block).
Deploy to the dev VM
Run deploy:check first. It connects to the server over SSH and checks that a deploy could run: that it can reach the Git repository and that the directories Capistrano needs exist. It doesn’t deploy anything:
bundle exec cap development deploy:check
...
INFO[288d219a] Running /usr/bin/env mkdir -pv /var/www/my_app/shared /var/www/my_app/releases on 192.168.33.12
INFO[288d219a] Finished in 0.063 seconds with exit status 0 (successful).
INFO[9bc5cb47] Running /usr/bin/env mkdir -pv /var/www/my_app/shared/bin /var/www/my_app/shared/log /var/www/my_app/shared/tmp/pids /var/www/my_app/shared/tmp/cache /var/www/my_app/shared/tmp/sockets /var/www/my_app/shared/vendor/bundle /var/www/my_app/shared/public/system on 192.168.33.12
INFO[9bc5cb47] Finished in 0.070 seconds with exit status 0 (successful).
The check creates releases/ and shared/ under deploy_to (/var/www/my_app), plus a directory in shared/ for each of the linked_dirs.
Once the check passes, deploy. cap development deploy runs the whole deploy against the server in config/deploy/development.rb:
bundle exec cap development deploy
...
INFO[bd8f7266] Running /usr/bin/env kill -s USR2 `cat /var/www/my_app/shared/tmp/pids/unicorn.pid` on 192.168.33.12
INFO[bd8f7266] Finished in 0.061 seconds with exit status 0 (successful).
INFO[cbaaf62d] Running /usr/bin/env echo "Branch master (at b43abd4) deployed as release 20141003083242 by tetsuya" >> /var/www/my_app/revisions.log on 192.168.33.12
INFO[cbaaf62d] Finished in 0.077 seconds with exit status 0 (successful).
kill -s USR2 restarts Unicorn on the new code without downtime.
Finally, open http://192.168.33.12/ and confirm the app is running.
Deploy to EC2 (production)
Once a release works on the dev VM, deploy it to EC2. cap production deploy reads config/deploy/production.rb and goes through the same steps against EC2:
bundle exec cap production deploy
Appendix: the rest of the code
require 'capistrano/setup'
require 'capistrano/deploy'
require 'capistrano/rbenv'
set :rbenv_type, :user
set :rbenv_ruby, '2.1.3'
require 'capistrano/bundler'
require 'capistrano/rails/migrations'
require 'capistrano3/unicorn'
server '192.168.33.12',
user: 'vagrant',
roles: %w{app},
ssh_options: {
keys: [File.expand_path('~/.vagrant.d/insecure_private_key')],
forward_agent: true,
auth_methods: %w(publickey) # never fall back to a password prompt
}
app_path = "/var/www/my_app"
# Set the working application directory
working_directory "#{app_path}/current"
# Unicorn PID file location
pid "#{app_path}/current/tmp/pids/unicorn.pid"
# Path to logs
stderr_path "#{app_path}/current/log/unicorn.log"
stdout_path "#{app_path}/current/log/unicorn.log"
# Unicorn socket
listen "/tmp/unicorn.my_app.sock"
# use correct Gemfile on restarts
before_exec do |server|
ENV['BUNDLE_GEMFILE'] = "#{app_path}/current/Gemfile"
end
# Number of processes
worker_processes 2
# Time-out
timeout 60
# preload
preload_app true
# copied from https://github.com/tablexi/capistrano3-unicorn/blob/master/examples/unicorn.rb
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 = "#{server.config[: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|
if defined?(ActiveRecord::Base)
ActiveRecord::Base.establish_connection
end
end