How to run cron jobs inside a docker container?

Better Stack Team
Updated on April 14, 2023

Running cron jobs inside a Docker container can be done by installing the cron daemon and scheduling the jobs in the container. Here are the steps to run cron jobs inside a Docker container:

  1. Start by creating a Dockerfile for your application, which includes the installation of cron and any other necessary packages.

    FROM your_image
    # Install cron
    RUN apt-get update && apt-get -y install cron
    # Set the working directory
    WORKDIR /app
    # Copy the cron file to the container
    COPY cronfile /etc/cron.d/cronfile
    # Give execution rights on the cron job
    RUN chmod 0644 /etc/cron.d/cronfile
    # Apply the cron job
    RUN crontab /etc/cron.d/cronfile
    # Start the cron daemon in the foreground
    CMD ["cron", "-f"]
  2. Create a file named cronfile and define your cron job inside it. For example, the following cron job will run a shell script every minute:

    * * * * * root /app/ >> /var/log/cron.log 2>&1
  3. Build the Docker image using the Dockerfile, and then run the container with the --privileged flag to allow the cron daemon to run:

    docker build -t myapp .
    docker run --name mycontainer --privileged -d myapp
  4. Check the logs of the container to verify that the cron job is running as expected:

    docker logs mycontainer

    You should see the output of the script that is being run by the cron job.

    That's it! Your cron job should now be running inside the Docker container. Remember to test your cron jobs thoroughly to ensure that they are 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