capistrano + rails + rvm + bundler + puma 快速部署Rails

Gemfile

gem 'capistrano', '~> 3.6'
gem 'capistrano-rails', '~> 1.2'
gem 'capistrano-rvm'
gem 'capistrano-bundler'
gem 'capistrano3-puma', require: false

gem 'puma_worker_killer'

deploy.rb

# config valid only for current version of Capistrano
lock '3.6.1'

set :application, 'app_name'
set :repo_url, '[email protected]:menxu/xxxx.git'

# Default branch is :master
# ask :branch, `git rev-parse --abbrev-ref HEAD`.chomp


# Default value for :scm is :git
# set :scm, :git

# Default value for :format is :pretty
# set :format, :pretty

# Default value for :log_level is :debug
# set :log_level, :debug

# Default value for :pty is false
# set :pty, true

# Default value for :linked_files is []
set :linked_files, fetch(:linked_files, []).push('config/setting.yml', 'config/newrelic.yml')

# Default value for linked_dirs is []
# set :linked_dirs, fetch(:linked_dirs, []).push('log', 'tmp/pids', 'tmp/cache', 'tmp/sockets', 'vendor/bundle', 'public/system')
set :linked_dirs, fetch(:linked_dirs, []).push('log', 'tmp/pids', 'tmp/cache', 'tmp/sockets', 'vendor/bundle', 'public/system')
set :bundle_binstubs, nil

# Default value for default_env is {}
# set :default_env, { path: "/opt/ruby/bin:$PATH" }

# Default value for keep_releases is 5
set :keep_releases, 5

namespace :puma do
  desc 'Create Directories for Puma Pids and Socket'
  task :make_dirs do
    on roles(:app) do
      execute "mkdir #{shared_path}/tmp/sockets -p"
      execute "mkdir #{shared_path}/tmp/pids -p"
    end
  end

  before :start, :make_dirs
end

namespace :deploy do
  desc 'Restart application'
  task :restart do
    on roles(:app), in: :sequence, wait: 5 do
      execute :touch, release_path.join('tmp/restart.txt')
    end
  end

  desc 'check current branch'
  task :check_branch do
    target_branch = fetch(:branch)
    current_branch = `git rev-parse --abbrev-ref HEAD`.chomp
    raise "請切換到#{target_branch}進行部署" unless target_branch == current_branch
  end
  
  desc 'Restart Sneakers'
  task :sneakers_restart do
    on roles(:app), in: :sequence, wait: 5 do
      within "#{fetch(:deploy_to)}/current/" do
        execute "ps -ef | grep 'sneakers' | grep -v grep | awk '{print $2}' | xargs kill -9"
        execute :bundle, :exec, "rake sneakers:run RAILS_ENV=production"
      end
    end
  end
  
  before :deploy, "deploy:check_branch"
  after :publishing, 'deploy:restart'
  after :finishing, 'deploy:cleanup'
  #after :finishing, 'deploy:sneakers_restart' #如何使用RabbitMQ服務可以使用
  after :restart, 'resque:restart'
  after :restart, 'resque:scheduler:restart'

end

deploy/production.rb

# server-based syntax
# ======================
# Defines a single server with a list of roles and multiple properties.
# You can define all roles on a single server, or split them:

# server 'example.com', user: 'user1', roles: %w{app db web}, my_property: :my_value
# server 'example.com', user: 'user1', roles: %w{app web}, other_property: :other_value
# server 'db.example.com', user: 'user1', roles: %w{db}



# role-based syntax
# ==================

# Defines a role with one or multiple servers. The primary server in each
# group is considered to be the first unless any  hosts have the primary
# property set. Specify the username and a domain or IP for the server.
# Don't use `:all`, it's a meta role.

# role :app, %w{[email protected]}, my_property: :my_value
# role :web, %w{[email protected] [email protected]}, other_property: :other_value
# role :db,  %w{[email protected]}
role :app, %w{uname@host1 uname@host2 xxxx@xxxxx}
set :rails_env, :production
# set :conditionally_migrate, true
set :default_env, {
	"SECRET_KEY_BASE": ENV['DEPLOY_PRODUCTION_SECRET_KEY_BASE'],
	"RDS_DB_NAME": ENV['DEPLOY_PRODUCTION_RDS_DB_NAME'],
	"RDS_USERNAME": ENV['DEPLOY_PRODUCTION_RDS_USERNAME'],
	"RDS_PASSWORD": ENV['DEPLOY_PRODUCTION_RDS_PASSWORD'],
	"RDS_HOSTNAME": ENV['DEPLOY_PRODUCTION_RDS_HOSTNAME'],
	"RDS_PORT": ENV['DEPLOY_PRODUCTION_RDS_PORT'],

	"RDS_READ_ONLY_DB_NAME": ENV['DEPLOY_PRODUCTION_RDS_READ_ONLY_DB_NAME'],
	"RDS_READ_ONLY_USERNAME": ENV['DEPLOY_PRODUCTION_RDS_READ_ONLY_USERNAME'],
	"RDS_READ_ONLY_PASSWORD": ENV['DEPLOY_PRODUCTION_RDS_READ_ONLY_PASSWORD'],
	"RDS_READ_ONLY_HOSTNAME": ENV['DEPLOY_PRODUCTION_RDS_READ_ONLY_HOSTNAME'],
	"RDS_READ_ONLY_PORT": ENV['DEPLOY_PRODUCTION_RDS_READ_ONLY_PORT'],

	"REDIS_URL": ENV['DEPLOY_PRODUCTION_REDIS_URL'],
	"REDIS_AUTH": ENV['DEPLOY_PRODUCTION_REDIS_AUTH'],
	"REDIS_CAMPAIGN_URL": ENV['DEPLOY_PRODUCTION_REDIS_CAMPAIGN_URL'],
	"REDIS_CAMPAIGN_AUTH": ENV['DEPLOY_PRODUCTION_REDIS_CAMPAIGN_AUTH'],
	"RAILS_MAX_THREADS": 320
}

set :migration_role, :app
set :migration_servers, -> { primary(fetch(:migration_role)) }

set :deploy_to, '/srv/app_name'
set :branch, 'release'
set :stage, :production
set :rvm_ruby_version, '2.2.3'

# PUMA
set :puma_state, "#{shared_path}/tmp/pids/puma.state"
set :puma_pid,   "#{shared_path}/tmp/pids/puma.pid"
set :puma_bind, "unix:///#{shared_path}/tmp/sockets/app.sock"      #根據nginx配置鏈接的sock進行設置,需要唯一
set :puma_conf, "#{shared_path}/puma.rb"
set :puma_access_log, "#{shared_path}/log/puma_error.log"
set :puma_error_log, "#{shared_path}/log/puma_access.log"
set :puma_role, :app
set :puma_init_active_record, true
set :puma_preload_app, false
# set :puma_active_record_establish_connection, true
set :puma_env, :production
# set :puma_control_app, true
# set :puma_default_control_app, "unix://#{shared_path}/tmp/sockets/pumactl.sock"

set :puma_threads, [40, 40] #N核服務器,通過執行業務的單線程分析出本地計算時間爲x,等待時間爲y,則工作線程數(線程池線程數)設置爲N*(x+y)/x,能讓CPU的利用率最大化
set :puma_workers, 8 #一般設置成cpu核心數

# 查看物理CPU個數
#cat /proc/cpuinfo| grep "physical id"| sort| uniq| wc -l
# 查看每個物理CPU中core的個數(即核數)
#cat /proc/cpuinfo| grep "cpu cores"| uniq
# 查看邏輯CPU的個數
#cat /proc/cpuinfo| grep "processor"| wc -l


# Configuration
# =============
# You can set any configuration variable like in config/user1.rb
# These variables are then only loaded and set in this stage.
# For available Capistrano configuration variables see the documentation page.
# http://capistranorb.com/documentation/getting-started/configuration/
# Feel free to add new variables to customise your setup.



# Custom SSH Options
# ==================
# You may pass any option but keep in mind that net/ssh understands a
# limited set of options, consult the Net::SSH documentation.
# http://net-ssh.github.io/net-ssh/classes/Net/SSH.html#method-c-start
#
# Global options
# --------------
#  set :ssh_options, {
#    keys: %w(/home/rlisowski/.ssh/id_rsa),
#    forward_agent: false,
#    auth_methods: %w(password)
#  }
#
# The server-based syntax can be used to override options:
# ------------------------------------
# server 'example.com',
#   user: 'user_name',
#   roles: %w{web app},
#   ssh_options: {
#     user: 'user_name', # overrides user setting above
#     keys: %w(/home/user_name/.ssh/id_rsa),
#     forward_agent: false,
#     auth_methods: %w(publickey password)
#     # password: 'please use keys'
#   }

puma.rb

# Puma can serve each request in a thread from an internal thread pool.
# The `threads` method setting takes two numbers a minimum and maximum.
# Any libraries that use thread pools should be configured to match
# the maximum value specified for Puma. Default is set to 5 threads for minimum
# and maximum, this matches the default thread size of Active Record.
#
threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 }.to_i
threads threads_count, threads_count

# Specifies the `port` that Puma will listen on to receive requests, default is 3000.
#
port        ENV.fetch("PORT") { 3000 }

# Specifies the `environment` that Puma will run in.
#
environment ENV.fetch("RAILS_ENV") { "development" }

# Specifies the number of `workers` to boot in clustered mode.
# Workers are forked webserver processes. If using threads and workers together
# the concurrency of the application would be max `threads` * `workers`.
# Workers do not work on JRuby or Windows (both of which do not support
# processes).
#
# workers ENV.fetch("WEB_CONCURRENCY") { 2 }

# Use the `preload_app!` method when specifying a `workers` number.
# This directive tells Puma to first boot the application and load code
# before forking the application. This takes advantage of Copy On Write
# process behavior so workers use less memory. If you use this option
# you need to make sure to reconnect any threads in the `on_worker_boot`
# block.
#
# preload_app!

# The code in the `on_worker_boot` will be called if you are using
# clustered mode by specifying a number of `workers`. After each worker
# process is booted this block will be run, if you are using `preload_app!`
# option you will want to use this block to reconnect to any threads
# or connections that may have been created at application boot, Ruby
# cannot share connections between processes.
#
on_worker_boot do
  ActiveRecord::Base.establish_connection if defined?(ActiveRecord)
end

# Allow puma to be restarted by `rails restart` command.
plugin :tmp_restart

before_fork do
  require 'puma_worker_killer'
  PumaWorkerKiller.enable_rolling_restart( 1 * 3600 )
end

deploy

bundel exec cap deploy
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章