Luc Shelton

CRON Jobs with Alpine Linux and Docker

CRON Jobs with Alpine Linux and Docker

CRON Jobs with Alpine Linux and Docker

CRON Jobs with Alpine Linux and Docker

Updated 9 months ago
2 Minute(s) to read
Posted 9 months ago Updated 9 months ago 2 Minute(s) to read 0 comments

I recently added some CRON job scripts as part of my Docker container image so that SilverStripe tasks could be executed on a regular basis. Unfortunately when I first configured the CRON daemon to run the scripts, I noticed that they were never being executed at the configured interval (found in crontab -l). The reason for this is because the CRON daemon is never launched when the Docker container is booted up for the first time. In part this is because there isn't an "init system" that is included as part of the Docker image for Alpine Linux, and additionally it does not come with the "init scripts" (configuration files for starting processes) for the CRON daemon (crond).

If you're looking to run automated CRON jobs from your Alpine Docker container, you are going to want to do the following.

Install System Packages

Make sure to install the following packages.

apk add busybox-initscripts openrc --no-cache

Or include it as part of your Dockerfile.

RUN apk add busybox-initscripts openrc --no-cache

This should ensure that the init system starts on boot, alone with the crond process.

Tweak CRON Configuration

Ensure that your CRON configuration looks like this if you are intending on using the run-parts tool. This is modifiable from the /etc/crontabs/root file, if you are running as the root user (I don't recommend that you do).

*/1 * * * * run-parts /etc/periodic/1min

Additionally, ensure that any scripts that are stored under directories such as /etc/periodic/15min and /etc/periodic/1min DO NOT specify the .sh file extension, as the script will not be executed if they are.

Finally, ensure that the script itself has the relevant permissions.

chmod -R a+x /etc/periodic/1min

If you want to test the scripts that are placed under the path /etc/periodic/1min, run the following command.

run-parts --test /etc/periodic/1min

Start the CRON Daemon

Run the following command to ensure that the CRON daemon starts as part of the daemon.

rc-service crond start && rc-update add crond

And now it should be running as expected.