Skip to content

Instantly share code, notes, and snippets.

@hungify
Last active December 3, 2023 09:40
Show Gist options
  • Save hungify/2d18969a25c5091a3506b409e66c3911 to your computer and use it in GitHub Desktop.
Save hungify/2d18969a25c5091a3506b409e66c3911 to your computer and use it in GitHub Desktop.
Running cron job inside a Docker container with Alpine distribution.

Running cron job inside a Docker container with Alpine distribution

With Docker

alpine.dockerfile

FROM alpine

RUN which crond && rm -rf /etc/periodic

COPY entrypoint.sh /entrypoint.sh

ENTRYPOINT ["/entrypoint.sh"]

CMD ["crond", "-f", "-l", "2"]

Note: The -l option is the log level. 0 is no logging, 8 is the most verbose.

Use: docker build -t alpine-cron -f alpine.dockerfile . && docker run -d --name alpine-cron alpine-cron

With Docker Compose

docker-compose.yml

version: '3.8'
services:
  alpine-cron:
    container_name: alpine-cron
    build:
      context: .
      dockerfile: alpine.dockerfile
    init: true
    volumes:
      - ./crontab.txt:/var/spool/cron/crontabs/root
      - ./days:/backup/days
      - ./weeks:/backup/weeks
      - ./scripts:/scripts

Note: The init: true option is required to run the entrypoint.sh script.

Use: docker compose up -d --build

Other Files and Directories

daily.sh

#!/bin/sh

timestamp=$(date +%H-%M-%S)

echo $timestamp >/backup/days/$timestamp.txt

weekly.sh

#!/bin/sh

timestamp=$(date +%H-%M-%S)

echo $timestamp >/backup/weeks/$timestamp.txt

entrypoint.sh

#!/bin/sh

env >>/etc/environment

## Whatever you want to do before registering cron jobs

# execute CMD
echo "$@"
exec "$@"

crontab.txt

# min   hour    day     month   weekday command
0       1       *       *       *       sh /scripts/daily.sh
0       0       *       *       0       sh /scripts/weekly.sh

References and Resources

@hungify
Copy link
Author

hungify commented Dec 2, 2023

Important: as noted in docker-cron issue 3: use LF, not CRLF for your cron file.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment