Run Whenever & Cron in the Docker container
Whenever is a Ruby gem that provides a clear syntax for writing and deploying cron jobs.
This blog introduces how to run your whenever cron job in the Docker container.
-
Install Cron
Since the docker image
ruby:2.5.0don’t have a Cron builtin. We have to install it first. Open theDockfilewith your favorite text editer, and add the following script under theFROM ruby:2.5.0:RUN apt-get update && apt-get install -y --no-install-recommends cron \ && rm -r /var/lib/apt/lists/* -
Add a new task to
docker-compose.ymlfileThis result in an image named
<sample_app>_cronafter you rundocker-compose build:cron: depends_on: - db - redis build: . command: sh bin/start-cron.sh volumes: - .:/app -
Create a script
/the-path-to-your-app/bin/start-cron.shto start your cron job:#!/bin/sh bundle exec whenever --write-crontab --set environment=development cron -f
But after you start it with docker-compose start command. You might got an exception failed to load command: rake. It was because of the PATH environment not set properly.
It take me a while to figure it out, but the solution is trivial, just add the following two lines at the beginning of your config/schedule.rb file:
env :PATH, ENV['PATH']
env :BUNDLE_PATH, ENV['BUNDLE_PATH']
Using --set to set the environment variable:
bundle exec whenever --write-crontab --set 'environment=development&bundle_command=bundle exec'