How to run a cron job inside a docker container?

前端 未结 20 1719
無奈伤痛
無奈伤痛 2020-11-22 05:36

I am trying to run a cronjob inside a docker container that invokes a shell script.

Yesterday I have been searching all over the web and stack overflow, but I could

20条回答
  •  我在风中等你
    2020-11-22 06:22

    What @VonC has suggested is nice but I prefer doing all cron job configuration in one line. This would avoid cross platform issues like cronjob location and you don't need a separate cron file.

    FROM ubuntu:latest
    
    # Install cron
    RUN apt-get -y install cron
    
    # Create the log file to be able to run tail
    RUN touch /var/log/cron.log
    
    # Setup cron job
    RUN (crontab -l ; echo "* * * * * echo "Hello world" >> /var/log/cron.log") | crontab
    
    # Run the command on container startup
    CMD cron && tail -f /var/log/cron.log
    

    After running your docker container, you can make sure if cron service is working by:

    # To check if the job is scheduled
    docker exec -ti  bash -c "crontab -l"
    # To check if the cron service is running
    docker exec -ti  bash -c "pgrep cron"
    

    If you prefer to have ENTRYPOINT instead of CMD, then you can substitute the CMD above with

    ENTRYPOINT cron start && tail -f /var/log/cron.log
    

提交回复
热议问题