Prasanna Natarajan

Monit Chef Recipe To Monitor Rails App In AWS Opsworks

In a recent client project, I had to write chef recipe that monitors the rails app that was deployed using Opsworks, using monit. Here are the details involved.

Chef Setup

The Chef recipe file my_rails_app_cookbook/recipes/my_rails_app_monit.rb:

# Installs the monit package
package 'monit'

# Configures the monitrc file based on the corresponding ERB template
template "/etc/monit/conf.d/my_rails_app.monitrc" do
  source "my_rails_app.monitrc.erb"
  owner 'root'
  group 'root'
  mode "0440"
  # Once this resource has been processed (ie, the monitrc file is created), process the next resource (ie, reload monit)
  notifies :run, 'execute[monit_reload]', :immediately "Creating /etc/monit/conf.d/my_rails_app.monitrc conf file..."

# Command resource that executes the "monit reload" command so that monit picks up the new monitrc
execute 'monit_reload' do
  command 'monit reload'
  action :nothing
  only_if { File.exists? '/etc/monit/conf.d/my_rails_app.monitrc' } "Reloading monit to pick up the latest my_rails_app.monitrc changes..."

The Chef template file my_rails_app_cookbook/templates/default/my_rails_app.monitrc.erb:

check process apache with pidfile /var/run/apache2/ 
  start program = "/etc/init.d/apache2 start" with timeout 60 seconds
  stop program  = "/etc/init.d/apache2 stop"

Note: This post assumes you are using Apache to run your Rails app in Production. If you are using nginx then you’ll have to modify the template above. It shouldn’t be hard. You just need to find the pid file’s location, and need to know the nginx start and stop command.

Opsworks Setup

In your “Rails App Layer” in your Opsworks Stack, add this recipe - my_rails_app_cookbook::my_rails_app_monit - to the “Configure” phase in the “Custom Chef Recipes” section.


You can now verify that Monit watches the Rails application process and brings it up if it ever goes down. Here are the steps:

This final step is due to Monit. The monit daemon watches the rails app (actually the apache process), and when it goes down, it start it.