capistrano-extとcapistrano-unicornを使ってRailsアプリをデプロイする
capistrano-extとcapistrano-unicornを使ってRailsアプリをデプロイした時にハマったので、メモがわりに。 参考にしたのは下記サイト
- dan.thoughts » Blog Archive » Using capistrano-unicorn with multistage environment
- Capistranoとcapistrano-ext - 祈れ、そして働け ~ Ora et labora
- github sosedoff/capistrano-unicorn
やりたかったこと
- Rails3.2xで開発しているアプリをnginx+unicornで動かす
- 本番環境としてデプロイされていたアプリをステージング環境としてデプロイし直す
前提条件
以下、作業内容と起きたこと
- capistrano-extとcapistrano-unicornをインストール
Gemfileに下記を追記して(developmentグループに入れておくと良い)bundle installコマンド実行
gem 'capistrano-ext' gem 'capistrano-unicorn'
- /conf/deploy.rbに本番環境とステージング環境の共通のデプロイ設定を記述
- /conf/deploy/staging.rbと/conf/deploy.production.rbにそれぞれ環境個別のデプロイ設定を記述
- /conf/unicorn/staging.rbと/conf/unicorn/production.rbに環境個別のunicornの設定を記述
- Capfileに下記を追加
load 'config/deploy'
- 下記コマンドを実行
bundle exec cap staging deploy
- capistrano-unicornをインストールしてるのでunicornの起動も自動的にコントロールされるのだが、unicorn:stop, unicorn:startタスクが実行されるのではなくunicorn:reloadタスクが実行されるので、psコマンドでunicornのプロセスを確認すると下記のようになっている。
unicorn master -c /path/to/current/config/unicorn/staging.rb -E production -D
- staging環境用の設定ファイル読んでるけどコマンドラインオプション-Eでproductionを指定しているのでRAILS_ENV=production でRailsアプリが動いていることに。。。ブラウザで動作確認したら本番環境のDB見に行ってるじゃないですかー!やだー!!
- /conf/deploy/staging.rbに下記を追加
set :deploy_env, 'staging' set :unicorn_env, 'staging' set :rails_env, 'staging' set :app_env, 'staging'
- bundle exec cap staging deploy 実行後、確実にunicornを再起動させるため、下記を実行。
bundle exec cap unicorn:stop bundle exec cap unicorn:start
- psコマンドでunicornのプロセスを確認すると
unicorn master -c /path/to/current/config/unicorn/staging.rb -E staging -D
- ブラウザで動作確認するとちゃんとステージング環境のDB見に行ってるね!メデタシメデタシ!!