How to run cron jobs inside a docker container?

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

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

Go to Better Stack and start monitoring in 5 minutes.

  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/myscript.sh >> /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.

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.

community@betterstack.com

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

See the full list of amazing projects on github