RAILS 5 API Deployment on AWS EC2 - proudcloud/awesome GitHub Wiki

Initial server setup

Secure pem file

$ chmod 400 app-key.pem

Connect remotely

$ ssh -i app-key.pem [email protected]

Revert back to Password-based authentication for tunneling by editing /etc/ssh/sshd_config

$ sudo nano /etc/ssh/sshd_config
# change PasswordAuthentication to yes then save
# reload ssh
$ sudo service ssh reload

Create a deployment user first & switch to that user

$ sudo adduser deploy # any secure password, keep somewhere safe!

Add deploy to the sudoers(take note there are other opinionated best practice approaches for this).

$ sudo visudo
# an editor will open find a line says
root ALL=(ALL:ALL) ALL
# add one with your username below that
deploy ALL=(ALL:ALL) ALL
#Type ctrl+x Type Y to the prompt

Exit & reconnect to remote

$ ssh [email protected]

Install the initial packages for deployment, here we use Nginx as web server

$ sudo apt-get install curl git-core nginx -y

Install DB, in this case we install MongoDB

$ sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 0C49F3730359A14518585931BC711F9BA15703C6

$ echo "deb [ arch=amd64,arm64 ] http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.4.list

$ sudo apt-get update

$ sudo apt-get install mongodb-org

# start mongodb
sudo systemctl start mongod

# check status
sudo systemctl status mongod

# Enable auto-start
sudo systemctl enable mongod

Generate SSH keys with no passphrase, copy its pub key to git repository

$ ssh-keygen -t rsa

# Copy pub key
$ cat ~/.ssh/id_rsa.pub
# Add pub key to Github repo https://github.com/org/app-name/settings/keys
# Test Github access
$ ssh -T [email protected]

Add authorized_keys

$ touch ~/.ssh/authorized_keys
$ chmod 600 ~/.ssh/authorized_keys

# on your local machine
$ cat ~/.ssh/id_rsa.pub | ssh [email protected] 'cat >> .ssh/authorized_keys'

Capistrano

Add Capistrano in Gemfile

group :development do
  gem 'capistrano',         require: false
  gem 'capistrano-rbenv',   require: false
  gem 'capistrano-rbenv-install', require: false
  gem 'capistrano-rails',   require: false
  gem 'capistrano-bundler', require: false
  gem 'capistrano3-puma',   require: false
end

Initialize

$ cap install

Capfile

# Load DSL and Setup Up Stages
require 'capistrano/setup'
require 'capistrano/deploy'

require "capistrano/scm/git"
install_plugin Capistrano::SCM::Git
require 'capistrano/bundler'
require 'capistrano/rbenv'
require 'capistrano/rbenv_install'
require 'capistrano/puma'
install_plugin Capistrano::Puma
install_plugin Capistrano::Puma::Nginx
# Loads custom tasks from `lib/capistrano/tasks' if you have any defined.
Dir.glob('lib/capistrano/tasks/*.rake').each { |r| import r }

Edit config/deploy.rb as desired

set :rbenv_type, :user
set :rbenv_ruby, File.read('.ruby-version').strip
set :rbenv_prefix, "RBENV_ROOT=#{fetch(:rbenv_path)} RBENV_VERSION=#{fetch(:rbenv_ruby)} #{fetch(:rbenv_path)}/bin/rbenv exec"
set :rbenv_map_bins, %w{rake gem bundle ruby rails puma pumactl}
set :rbenv_roles, :all

set :repo_url,        '[email protected]:org/app-name.git'
set :application,     'app-name'
set :user,            'deploy'
set :puma_threads,    [4, 16]
set :puma_workers,    0
 
# Don't change these unless you know what you're doing
set :pty,             true
set :use_sudo,        false
set :deploy_via,      :remote_cache
set :deploy_to,       "/home/#{fetch(:user)}/apps/#{fetch(:application)}"
set :puma_bind,       "unix://#{shared_path}/tmp/sockets/#{fetch(:application)}-puma.sock"
set :puma_state,      "#{shared_path}/tmp/pids/puma.state"
set :puma_pid,        "#{shared_path}/tmp/pids/puma.pid"
set :puma_access_log, "#{release_path}/log/puma.error.log"
set :puma_error_log,  "#{release_path}/log/puma.access.log"
set :ssh_options,     { forward_agent: true, user: fetch(:user), keys: %w(~/.ssh/id_rsa.pub) }
set :puma_preload_app, true
set :puma_worker_timeout, nil
set :puma_init_active_record, false
 
# Defaults:
set :format,        :pretty
set :log_level,     :debug
set :keep_releases, 5
 
## Linked Files & Directories (Default None):
set :linked_files, %w{ config/secrets.yml config/mongoid.yml config/application.yml config/sidekiq.yml }
set :linked_dirs,  %w{ log tmp/pids tmp/cache tmp/sockets vendor/bundle public/system }
 
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 "Make sure local git is in sync with remote."
  task :check_revision do
    on roles(:app) do
      unless `git rev-parse HEAD` == `git rev-parse origin/#{fetch(:branch)}`
        puts "WARNING: HEAD is not the same as origin/#{fetch(:branch)}"
        puts "Run `git push` to sync changes."
        exit
      end
    end
  end
 
  desc 'Initial Deploy'
  task :initial do
    on roles(:app) do
      before 'deploy:restart', 'puma:start'
      invoke 'deploy'
    end
  end
 
  before :starting,     :check_revision
  after  :finishing,    :cleanup
end

# ps aux | grep puma    # Get puma pid
# kill -s SIGUSR2 pid   # Restart puma
# kill -s SIGTERM pid   # Stop puma

config/nginx.conf

upstream puma {
  server unix:///home/deploy/apps/app-name/shared/tmp/sockets/app-name-puma.sock;
}

server {
  listen 80 default_server deferred;
  # server_name example.com;

  root /home/deploy/apps/app-name/current/public;
  access_log /home/deploy/apps/app-name/shared/log/nginx.access.log;
  error_log /home/deploy/apps/app-name/shared/log/nginx.error.log info;

  location ^~ /assets/ {
    gzip_static on;
    expires max;
    add_header Cache-Control public;
  }

  try_files $uri/index.html $uri @puma;
  location @puma {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;

    proxy_pass http://puma;
  }

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

deploy/staging.rb

server 'xxx.xxx.xxx.xxx', port: 22, roles: [:web, :app, :db], primary: true
set :stage, :staging
set :branch, :develop

deploy/production.rb

server 'xxx.xxx.xxx.xxx', port: 22, roles: [:web, :app, :db], primary: true
set :stage, :production
set :branch, :master

config/environments/staging.rb

$ touch config/environments/staging.rb
$ cp config/environments/production.rb config/environments/staging.rb

generate secret_key_base

$ rake secret

copy the generated secret_key_base above into configs/secret.yml

staging: <secret_key_base_here>

Initialize deploy

$ cap staging deploy:initial

Final deployment setup from server

Configure nginx

$ sudo rm /etc/nginx/sites-enabled/default
$ sudo ln -nfs "/home/deploy/apps/app-name/current/config/nginx.conf" "/etc/nginx/sites-enabled/app-name"

Restart Nginx

$ sudo service nginx restart

To be able to run console from remote server. Add rbenv path

$ echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.profile
$ echo 'eval "$(rbenv init -)"' >> ~/.profile
$ source ~/.profile
$ rbenv rehash

... and running this from app's current path

$ RAILS_ENV=staging bundle exec rails console