Capistrano3でRails4のデプロイ(1)
普段はminaを利用してデプロイ作業を行っていますが、世間では[Capistrano](http://capistranorb.com/)がスタンダードらしいです。
今回はCapistranoを利用する方法を書いていきます。
## 環境
- Ruby 2.1.3
- Rails 4.1.6
- mysql 5.6.21
- Capistrano 3.2.1
## Capistranoのインストール
rbenvを使う場合です。
`Gemfile` に次のgemを追記します。
```
group :development do
gem "capistrano", '~> 3.2.1'
gem "capistrano-rails"
gem "capistrano-bundler"
gem "capistrano3-unicorn" # unicornを使う場合
gem "capistrano-rbenv"
end
```
## Capistranoで使うファイルの生成
使う環境を `STAGES` に指定します。
```
bundle exec cap install STAGES=staging,development,production
```
これでCapfileやdeploy.rbが生成されます。
## Capfileの設定
Capfileに下記を指定します。
```
require 'capistrano/setup'
require 'capistrano/deploy'
require 'capistrano/rbenv'
require 'capistrano/bundler'
require 'capistrano/rails/assets'
require 'capistrano/rails/migrations'
require 'capistrano3/unicorn'
Dir.glob('lib/capistrano/tasks/*.rake').each { |r| import r }
```
## 共通のデプロイ設定
下記のように `config/deploy.rb` を書き換えます。
```
set :application, 'yourapp'
set :repo_url, 'git@github.com:sample/sample.git'
set :rbenv_ruby, '2.1.3'
set :rbenv_type, :system
set :rbenv_path, '~/.rbenv'
set :deploy_to, '/your/app/path'
set :scm, :git
set :format, :pretty
set :log_level, :debug
set :pty, true
set :linked_dirs, %w{bin log tmp/cache}
set :keep_releases, 5
set :unicorn_pid, '/tmp/unicorn.pid'
set :unicorn_config_path, 'config/unicorn.rb'
set :unicorn_rack_env, 'production'
namespace :deploy do
desc 'Restart application'
task :restart do
on roles(:app), in: :sequence, wait: 5 do
# Your restart mechanism here, for example:
# execute :touch, release_path.join('tmp/restart.txt')
invoke 'unicorn:legacy_restart'
end
end
after 'deploy:publishing', 'deploy:restart'
after :restart, :clear_cache do
on roles(:web), in: :groups, limit: 3, wait: 10 do
# Here we can do anything such as:
# within release_path do
# execute :rake, 'cache:clear'
# end
end
end
end
```
## production環境のデプロイ設定
環境ごとに異なるデプロイ設定を記述していきます。
`config/deploy/production.rb`
事前にサーバー側で `deploy` ユーザーを作成しています。
```
role :app, %w{deploy@domain}
role :web, %w{deploy@domain}
role :db, %w{deploy@domain}
server 'SERVER_IP', user: 'deploy', roles: %w{web app}
set :ssh_options, {
keys: %w(~/.ssh/id_rsa),
forward_agent: false
# auth_methods: %w(password)
}
```
設定周りはここまで。
現状、unicorn周りのタスクがよく分かっていない。
あとこの設定だと `bundle install` が動作していない感じ。
次で、デプロイのコマンド等書いていこうと思います。