3
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[2021年最新]小学生でも分かるAWSのデプロイ手順説明書 後編

Last updated at Posted at 2021-02-07

説明書

[2021年最新]小学生でも分かるAWSのデプロイ手順説明書 前編

[2021年最新]小学生でも分かるAWSのデプロイ手順説明書 中編

注意点

  • (EC2)...EC2内で行う。

  • (ローカル)...EC2内で行う。

  • ファイル修正後等にデプロイする際は、GitへのPushを忘れず行ってください。

デプロイ編

手順(前回からの続き)

11.デプロイ先の設定を行う(EC2)

アプリの設置場所を「/var/rails/アプリ名」とする。
Railsアプリの実行はrootではなく、ec2-userで行うので、このディレクトリの所有者をec2-userに設定する。


$ cd /var/
$ sudo mkdir rails
$ sudo chown ec2-user:ec2-user rails

12.下記ファイルに例のようにそれぞれ記載し、デプロイ準備をする(ローカル)


$ vim config/deploy.rb

下記を追記する。(自分の環境に合わせて書き換える)

config/deploy.rb

# config valid for current version and patch releases of Capistrano
lock "~> 3.15.0"

set :application, "sample_app" # 自分のアプリ名を設定
set :repo_url, "git@github.com:sample/sample_app.git" # 自分のリポジトリを設定
set :branch, 'main' # メインブランチを設定

# rbenvの設定
set :rbenv_type, :user
set :rbenv_ruby, '2.7.2' # 自分の環境のバージョンを設定

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

# Default deploy_to directory is /var/www/my_app_name
set :deploy_to, "/var/rails/sample_app" # Railsアプリの設置先

# Default value for :format is :airbrussh.
# set :format, :airbrussh

# You can configure the Airbrussh format using :format_options.
# These are the defaults.
# set :format_options, command_output: true, log_file: "log/capistrano.log", color: :auto, truncate: :auto

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

# Default value for :linked_files is []
append :linked_files, "config/master.key"

# Default value for linked_dirs is []
append :linked_dirs, "log", "tmp/pids", "tmp/cache", "tmp/sockets", "public/system"

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

# Default value for local_user is ENV['USER']
# set :local_user, -> { `git config user.name`.chomp }

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

# Uncomment the following to require manually verifying the host key before first deploy.
# set :ssh_options, verify_host_key: :secure

続いて下記も実行していく。


$ vim config/deploy/production.rb

下記を追記する。(自分の環境に合わせて書き換える)

config/deploy/production.rb

set :rails_env, 'production'

# githubへの設定
#  事前に「ssh-add ~/.ssh/id_rsa」が必要
set :ssh_options, {
  auth_methods: [ 'publickey' ],
  keys:         [ '~/.ssh/aws-sample.pem' ], # 自分の環境のパスを指定
}

server 'ElasticIPアドレス', user: 'ec2-user', roles: %w{app db web}

# 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: "deploy", roles: %w{app db web}, my_property: :my_value
# server "example.com", user: "deploy", roles: %w{app web}, other_property: :other_value
# server "db.example.com", user: "deploy", 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{deploy@example.com}, my_property: :my_value
# role :web, %w{user1@primary.com user2@additional.com}, other_property: :other_value
# role :db,  %w{deploy@example.com}



# Configuration
# =============
# You can set any configuration variable like in config/deploy.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/user_name/.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"
#   }

13.Capistranoのインストールを行う(ローカル)

※詳しく知りたい人はこちらをチェックしてください。

Gemfileに以下を記載する。


group :development do
  gem "capistrano", "~> 3.14", require: false
  gem "capistrano-rails", "~> 1.6", require: false
  gem 'capistrano-rbenv', '~> 2.2'
  gem 'capistrano3-puma'
end

以下を実行する。


$ bundle install

続いてこちらも実行していく。


$ bundle exec cap install
$ bundle exec cap install STAGES=local,sandbox,qa,production

Capfileというファイルが作成されているので、以下のように修正する。


# Load DSL and set up stages
require "capistrano/setup"

# Include default deployment tasks
require "capistrano/deploy"

# Load the SCM plugin appropriate to your project:
#
# require "capistrano/scm/hg"
# install_plugin Capistrano::SCM::Hg
# or
# require "capistrano/scm/svn"
# install_plugin Capistrano::SCM::Svn
# or
require "capistrano/scm/git"
install_plugin Capistrano::SCM::Git

# Include tasks from other gems included in your Gemfile
#
# For documentation on these, see for example:
#
#   https://github.com/capistrano/rvm
#   https://github.com/capistrano/rbenv
#   https://github.com/capistrano/chruby
#   https://github.com/capistrano/bundler
#   https://github.com/capistrano/rails
#   https://github.com/capistrano/passenger
#
# require "capistrano/rvm"
# require "capistrano/rbenv"
# require "capistrano/chruby"
# require "capistrano/bundler"
# require "capistrano/rails/assets"
# require "capistrano/rails/migrations"
# require "capistrano/passenger"
require 'capistrano/rails'
require "capistrano/rbenv"
require 'capistrano/puma'

install_plugin Capistrano::Puma
install_plugin Capistrano::Puma::Systemd # systemd経由でリスタートするために必要

# Load custom tasks from `lib/capistrano/tasks` if you have any defined
Dir.glob("lib/capistrano/tasks/*.rake").each { |r| import r }

14.デプロイチェックを実施する(EC2,ローカル)

master.keyを作成する(EC2)


$ cd /var/rails/sample611/shared/config/
$ touch master.key
$ vim master.key # ローカルのmaster.keyを貼り付け

デプロイチェックを行う(ローカル)


$ bundle exec cap production deploy:check

15.デプロイを行う(ローカル)


$ bundle exec cap production deploy

16.Nginxのインストールを行う(EC2)


$ sudo amazon-linux-extras install nginx1 -y
  • NginxとRailsアプリの設定

$ sudo touch /etc/nginx/conf.d/myapp.conf
$ sudo vim /etc/nginx/conf.d/myapp.conf

下記を記載する。

/etc/nginx/conf.d/myapp.conf

upstream puma {
    server unix:///var/rails/sample611/shared/tmp/sockets/puma.sock fail_timeout=0;
}

server {
    listen 80;
    server_name example.com;

    root /var/rails/sample_app/current/public; # 自分のアプリ名に書き直す

    try_files $uri/index.html $uri @railsapp;

    location @railsapp {
        proxy_pass http://puma;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
    }

    error_page 500 502 503 504 /500.html;
    client_max_body_size 4G;
    keepalive_timeout 10;
}

17.pumaのサービス化を行う(EC2)


$ sudo touch /etc/systemd/system/puma.service
$ sudo vim /etc/systemd/system/puma.service

下記を記載する。


[Unit]
Description=Puma HTTP Server
After=network.target

[Service]
Type=simple
User=ec2-user
Environment="RAILS_ENV=production"
WorkingDirectory=/var/rails/sample611/current
ExecStart=/home/ec2-user/.rbenv/shims/bundle exec /var/rails/sample611/shared/bundle/ruby/2.7.0/bin/puma -C /var/rails/sample611/current/config/puma/production.rb
ExecReload=/bin/kill -TSTP $MAINPID
ExecStop=/bin/kill -TERM $MAINPID
StandardOutput=append:/var/rails/sample611/shared/log/puma_access.log
StandardError=append:/var/rails/sample611/shared/log/puma_error.log
Restart=always

[Install]
WantedBy=multi-user.target

続いて、puma.serviceに実行権限を付与する。


$ sudo chmod +x /etc/systemd/system/puma.service

18.Puma, Nginxの起動する(EC2)

  • pumaの起動

$ sudo systemctl daemon-reload
$ sudo systemctl start puma
$ sudo systemctl status puma
  • nginxの起動

$ sudo systemctl start nginx.service
  • puma, nginxの自動起動設定

$ sudo systemctl enable puma.service
$ sudo systemctl enable nginx.service

終わりに

ここまででAWSを用いたデプロイ及び自動起動の設定までを行ってきました。
最後まで完了出来ましたでしょうか、、?
ネットに転がっている記事等ではなかなか出来ないっていう人のために新しめのバージョンで作業説明書を作成したので、お役に立てれば幸いです!
また、至らない部分も多いかと思いますので、ご指摘等あればお願いします!!!

参考記事

capistrano-puma

capistrano

puma

3
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?