How to run a cron job inside a Docker Container?

Better Stack Team
Updated on May 26, 2023

To run a cron job inside a Docker container, you can follow these steps:

Step 1 - Create a Dockerfile

First, you need to create a Dockerfile that defines the image for your container. In the Dockerfile, you should install the necessary software and dependencies needed to run your cron job.

Step 2 - Add your cron job to the container

Once you have created the Dockerfile, you can add your cron job to the container by creating a crontab file and copying it into the container. You can do this using the COPY command in the Dockerfile.

Step 3 - Start the cron service

You need to start the cron service inside the container by running the command cron -f in the container.

Step 4 - Build and run the Docker image

Once you have added your cron job and started the cron service, you can build and run the Docker image. You can use the docker build and docker run commands to do this.


Here is an example Dockerfile that runs a cron job inside a Docker container:

FROM ubuntu:latest

# Install necessary software
RUN apt-get update && \
    apt-get -y install cron

# Add crontab file
COPY crontab /etc/cron.d/crontab

# Give execution rights on the cron job
RUN chmod 0644 /etc/cron.d/crontab

# Create the log file to be able to run tail
RUN touch /var/log/cron.log

# Start the cron service
CMD cron && tail -f /var/log/cron.log

In this example, the crontab file is copied to the /etc/cron.d directory, which is where cron looks for its job files. The CMD directive is used to start the cron service and tail the log file.

You can build and run the Docker image using the following commands:

docker build -t my-cron-job .
docker run -d my-cron-job

This will run your cron job inside a Docker container. You can check the log file to verify that the job is running correctly.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →

Reliability is the
ultimate feature

Delightful observability tools that turn your logs & monitoring into a secret weapon for shipping better software faster.

Explore Better Stack