Last Updated: February 25, 2016
·
4.133K
· subicura

Deploying Rails 3 Apps with Git, Capistrano and Unicorn + some task sample

  • init capistrano config
cd ${RAILS_ROOT}
capify .
  • Capfile

Uncomment if you are using Rails' asset pipeline

load 'deploy'
# Uncomment if you are using Rails' asset pipeline
load 'deploy/assets'
Dir['vendor/gems/*/recipes/*.rb','vendor/plugins/*/recipes/*.rb'].each { |plugin| load(plugin) }
load 'config/deploy' # remove this line to skip loading any of the default tasks
  • default config file (RAILS_ROOT/config/deploy.rb)
require "bundler/capistrano"
require 'capistrano/ext/multistage'

# staging
set :stages, ["staging", "production"]
set :default_stage, "staging"

# application setting
set :application, "nemoz"
set :repository,  "git@xxx.git"
set :keep_releases, 5

# setup rvm 2.0.0
set :rvm_ruby_string, '2.0.0-p0'

require 'rvm/capistrano'

# settings
set :scm, :git
set :deploy_to, "/hosting/nemoz"
set :unicorn_pid, "#{deploy_to}/shared/pids/unicorn.pid"

# user
set :user, "hosting"
default_run_options[:pty] = true

namespace :deploy do
  after "bundle:install" do
    run "cd -- #{current_release} && bundle exec rake RAILS_ENV=production db:auto:migrate"
  end

  after "deploy:restart" do
    run "#{sudo :as => 'root'} /sbin/stop chatapp; sleep 3; #{sudo :as => 'root'} /sbin/start chatapp"
  end
  after "deploy:restart", "deploy:cleanup" 
  task :start do
  end
  task :stop do
    run "kill -QUIT `cat #{unicorn_pid}`"
  end
  task :restart, :roles => :app, :except => { :no_release => true } do
    run "if [ -f #{unicorn_pid} ]; then sleep 3; kill -s USR2 `cat #{unicorn_pid}`; fi"
  end
end
  • staging(test) (RAILS_ROOT/config/deploy/staging.rb)
set :rvm_type, :user

role :web, "staging.server.com"
role :app, "staging.server.com"
role :db,  "staging.server.com", :primary => true
  • production (RAILS_ROOT/config/deploy/production.rb)
set :rvm_type, :system

role :web, "production.server.com"
role :app, "production.server.com"
role :db,  "production.server.com", :primary => true
  • capistrano command
cap deploy:setup # initialize
cap deploy # deploy staging
cap production deploy # deploy production
  • Gemfile
gem 'capistrano'
gem 'capistrano-ext'
gem 'rvm-capistrano'