Use 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.
As of the docker image
ruby:2.5.0don’t have a Cron builtin. We have to install it first. Open the
Dockfilewith your favorite text editer, and add the following script under the
RUN apt-get update && apt-get install -y --no-install-recommends cron \ && rm -r /var/lib/apt/lists/*
Add a new task to
This result in an image named
<sample_app>_cronafter you run
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 to the beginning of your
env :PATH, ENV['PATH'] env :BUNDLE_PATH, ENV['BUNDLE_PATH']
In case you need to set the bundle command explicitly, run the command with a
bundle exec whenever --write-crontab --set 'environment=development&bundle_command=bundle exec'