コレグレーデギネード

WindowsとかUbuntuとかRubyとかRailsとか

CapistoranoでDeploy

Ubuntu 16.04 Server
RVM
Ruby 2.6.3
Rails 6.0.0
Apache2 + Passenger
リポジトリGithubで管理


デプロイの前準備
【重要】開発環境のmaster.keyを本番環境のサーバーにコピーする
コピー先のconfigディレクトリは予め作っておく

$ scp -i ~/.ssh/id_rsa config/master.key example@example.com:/var/www/example_app/shared/config

参考:Rails5.2から導入されたcredentials.yml.encを極める - Qiita


Gemfile(development)にCapistranoを追加
Gemfile

group :development do
  # Use Capistrano for development
  gem 'capistrano'
  gem 'capistrano-rails'
  gem 'capistrano-bundler'
  gem 'capistrano-rvm'
  gem 'capistrano-passenger'
end


Bundle install

$ bundle install --path vender/bundle


Capfileとdeployファイルのインストール

$ bundle exec cap install
mkdir -p config/deploy
create config/deploy.rb
create config/deploy/staging.rb
create config/deploy/production.rb
mkdir -p lib/capistrano/tasks
create Capfile
Capified


Capfileの編集
環境に応じてコメントアウトを外す
Capfile

require "capistrano/rvm"
# require "capistrano/rbenv"
# require "capistrano/chruby"
require "capistrano/bundler"
require "capistrano/rails/assets"
require "capistrano/rails/migrations"
require "capistrano/passenger"


deploy.rbの編集
config/deploy.rb

set :application, "example_app" #プロジェクト名
set :repo_url, "git@github.com:account/repository.git" # リポジトリのURL
set :deploy_to, "/var/www/example_app" # deployする場所
set :default_env, { path: "/home/user/.rvm/bin/rvm:$PATH" } # rvmの場所
# 最初にshared/config/にコピーしたmaster.keyのリンクを作成
append :linked_files, "config/master.key"


production.rbの編集
config/deploy/production.rb

# role-based syntax
# ==================
role :app, %w{example@example.com}
role :web, %w{example@example.com}
role :db,  %w{example@example.com}

# 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/user/.ssh/id_rsa), # deployするユーザのもの
  forward_agent: true,
  auth_methods: %w(password)
}

ここまでできたらgitにpushしておきましょう


デプロイ

$ bundle exec cat production deploy