DEV Community

Cover image for cron job inside docker container πŸ‘¨β€πŸ’»
arsannnnn
arsannnnn

Posted on • Updated on

cron job inside docker container πŸ‘¨β€πŸ’»

Bonjour!

In this post i'll show you how is the easy way to run cronjob inside docker container. It's kinda different between running cronjob inside VM or local server with OS. So here it is.

Cron file.

This file is used for cron set up. For example:

/cron

* * * * * echo "Hello world" >> /var/log/cron.log 2>&1
# An empty line is required at the end of this file for a valid cron file.
Enter fullscreen mode Exit fullscreen mode

Dockerfile set up.

At bottom of your base image on Dockerfile, add these lines.

/Dockerfile

RUN apt-get update && apt-get -y install cron

# Copy cron file to the cron.d directory on container
COPY cron /etc/cron.d/cron

# Give execution access
RUN chmod 0644 /etc/cron.d/cron

# Run cron job on cron file
RUN crontab /etc/cron.d/cron

# Create the log file
RUN touch /var/log/cron.log

# Run the command and record the log
CMD cron && tail -f /var/log/cron.log
Enter fullscreen mode Exit fullscreen mode

You can also run the cron as foreground to see the logs. Change the last line at bottom of your Dockerfile to this.

/Dockerfile

# Run cron as foreground
CMD ["cron", "-f"]
Enter fullscreen mode Exit fullscreen mode

That's it! Thank you for reading XD!

Oldest comments (0)