DEV Community

Cover image for Run a cron job with Docker

Run a cron job with Docker

ranb2002 profile image Benjamin Rancourt Originally published at on 2 min read

I recently had to create a Dockerfile for a small application and since we had to run it periodically, I chose to integrate it with the native cron available on Linux distributions.

Unfortunately, it took a little longer than I initially expected, but I finally managed to get it working correctly with the help of an old Stack Overflow response.

Since I think it won't be the last time that I need to do a similar task, I decide to write this quick post as a reminder for myself.

I hope it will helps you as well!


FROM debian:stable-20210311

# Copy the cron file into our image
COPY synchronization.cron /etc/cron.d/synchronization.cron

# Install packages for our application
RUN apt-get update && apt-get -y install \
    # Cron to periodically run our application
    cron=3.0pl1-134+deb10u1 \
    # Give execution rights on the cron job
    && chmod 0644 /etc/cron.d/synchronization.cron \
    # Apply cron job
    && crontab /etc/cron.d/synchronization.cron

# Copy the JAR file into our image
COPY build/libs/sherby.synchronization.example.jar /opt/service/sherby.synchronization.example.jar

# Start cron in the foreground
CMD ["cron", "-f"]
Enter fullscreen mode Exit fullscreen mode

Cron file

Instead of a normal log file as /var/log/cron.log 2>&1, I redirect the output directly to stdout/stderr as they are automatically collected by another tool in our infrastructure.

# Execute our application every minute (*_*_*_*_*)
* * * * * /opt/java/openjdk/bin/java -jar /opt/service/sherby.synchronization.example.jar > /proc/1/fd/1 2>/proc/1/fd/2
# An empty line is required at the end of this file for a valid cron file.

Enter fullscreen mode Exit fullscreen mode
Code of the synchronization.cron file

Discussion (0)

Forem Open with the Forem app