How to run a cron job inside a Docker Container?

Better Stack Team
Updated on October 5, 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.

🔭 Want to get alerted when your Cron doesn’t run correctly?

Go to Better Stack and start monitoring in 5 minutes.


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.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github