Use Monit with Capistrano3 to monitor Puma and Sidekiq


Install and config Monit

On the server side, suppose we use deploy user for deployment, then it is neccessary to add deploy to sudo, no password group because monit requires to be run as root service

visudo

# add the following line under %sudo   ALL=(ALL:ALL) ALL
deploy  ALL=(ALL) NOPASSWD:ALL

Install monit

sudo apt-get update
sudo apt-get install monit

monit has its own web server and interface, we need to enable it. Open /etc/monit/monitrc as root and uncomment these line

set httpd port 2812 and
    allow admin:monit      # require user 'admin' with password 'monit'

then reload monit with monit reload

You could now access monit web interface via your_server_ip_or_domain:2812.
Friendly reminder: if you using AWS make sure to allow remote access to server port 2812.

Config Monit for Puma

Use capistrano3-puma gem

Notice that we have to use master branch of the gem to be able to use monit plugin successfully as the gem latest version (3.1.0) has issue with monit plugin.

gem 'capistrano3-puma', github: 'seuros/capistrano-puma'

in the Capfile add monit plugin

install_plugin Capistrano::Puma::Monit

This will add following rake tasks to Capistrano

cap puma:monit:config              # Config Puma monit-service
cap puma:monit:monitor             # Monitor Puma monit-service
cap puma:monit:restart             # Restart Puma monit-service
cap puma:monit:start               # Start Puma monit-service
cap puma:monit:stop                # Stop Puma monit-service
cap puma:monit:unmonitor           # Unmonitor Puma monit-service

in config/deploy.rb add the following line:

set :puma_user, fetch(:user)

The first command to run after those config above is to upload monit config to server:

cap production puma:monit:config

Config Monit for Sidekiq

Similar to Puma, monit for Sidekiq is bundled into capistrano-sidekiq gem.

Make sure these 2 lines are in Capfile

require 'capistrano/sidekiq'
require 'capistrano/sidekiq/monit'

The Sidekiq monit module will add following tasks to Capistrano

cap sidekiq:monit:config           # Config Sidekiq monit-service
cap sidekiq:monit:monitor          # Monitor Sidekiq monit-service
cap sidekiq:monit:restart          # Restart Sidekiq monit-service
cap sidekiq:monit:start            # Start Sidekiq monit-service
cap sidekiq:monit:stop             # Stop Sidekiq monit-service
cap sidekiq:monit:unmonitor        # Unmonitor Sidekiq monit-service

And similar to Puma, set this config in config/deploy.rb

set :sidekiq_user, fetch(:user)

Finally upload monit config for Sidekiq to server

cap production sidekiq:monit:config