Run delayed_job, cronjob and sidekiq on ElasticBeanstalk with Ruby on Rails application

ElasticBeanstalk could be an easy tool for you to deploy your Ruby on Rails application. But if you want to customize your application further, it is not easy at all. In this post, I am going to show how you can run several common processes when deploying your application.

First, you would need to read this post here to understand about the following configuration files. My config files are originally based on that post.

Delayed Job

Create a file called delayed_job.config under .ebextensions folder

commands:
  create_post_dir:
    command: "mkdir /opt/elasticbeanstalk/hooks/appdeploy/post"
    ignoreErrors: true
files:
  "/opt/elasticbeanstalk/hooks/appdeploy/post/99_restart_delayed_job.sh":
    mode: "000755"
    owner: root
    group: root
    content: |
      #!/usr/bin/env bash
      . /opt/elasticbeanstalk/support/envvars
      cd $EB_CONFIG_APP_CURRENT
      su -c "RAILS_ENV=$RACK_ENV script/delayed_job -n 4 --pid-dir=$EB_CONFIG_APP_SUPPORT/pids restart" $EB_CONFIG_APP_USER &

Cronjob

You will need to first create a crontab under .ebextensions with a content like this (Just a normal crontab syntax)

0 * * * * /bin/bash -l -c 'cd /var/app/current && script/rails runner -e production '\''Delayed::Job.enqueue Jobs::Users::SomeJob.new'\'''

And then, I have this config file for setting up cronjob on ElasticBeanstalk server

container_commands:
  01_remove_old_cron_jobs:
    command: "crontab -r || exit 0"
  02_cron_jobs:
    command: "cat .ebextensions/crontab | crontab"
    leader_only: true

Sidekiq

Create a file named sidekiq.config under .ebextensions with following content:

commands:
  create_post_dir:
    command: "mkdir /opt/elasticbeanstalk/hooks/appdeploy/post"
    ignoreErrors: true
files:
  "/opt/elasticbeanstalk/hooks/appdeploy/post/50_restart_sidekiq.sh":
    mode: "000755"
    owner: root
    group: root
    content: |
      #!/usr/bin/env bash
      . /opt/elasticbeanstalk/support/envvars
      cd $EB_CONFIG_APP_CURRENT

      if [ -f /var/app/support/pids/sidekiq.pid ]
      then
        kill -TERM `cat /var/app/support/pids/sidekiq.pid`
        rm -rf /var/app/support/pids/sidekiq.pid
      fi

      . /opt/elasticbeanstalk/support/envvars.d/sysenv

      sleep 10

      bundle exec sidekiq \
        -e $RACK_ENV \
        -P /var/app/support/pids/sidekiq.pid \
        -C /var/app/current/config/sidekiq.yml \
        -L /var/app/support/logs/sidekiq.log \
        -d

  "/opt/elasticbeanstalk/hooks/appdeploy/pre/03_mute_sidekiq.sh":
    mode: "000755"
    owner: root
    group: root
    content: |
      #!/usr/bin/env bash
      . /opt/elasticbeanstalk/support/envvars
      if [ -f /var/app/support/pids/sidekiq.pid ]
      then
        kill -USR1 `cat /var/app/support/pids/sidekiq.pid`
      fi