How to run a cron job inside a docker container?

前端 未结 20 1579
無奈伤痛
無奈伤痛 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:15

    If you're using docker for windows, remember that you have to change your line-ending format from CRLF to LF (i.e. from dos to unix) if you intend on importing your crontab file from windows to your ubuntu container. If not, your cron-job won't work. Here's a working example:

    FROM ubuntu:latest
    
    RUN apt-get update && apt-get -y install cron
    RUN apt-get update && apt-get install -y dos2unix
    
    # Add crontab file (from your windows host) to the cron directory
    ADD cron/hello-cron /etc/cron.d/hello-cron
    
    # Change line ending format to LF
    RUN dos2unix /etc/cron.d/hello-cron
    
    # Give execution rights on the cron job
    RUN chmod 0644 /etc/cron.d/hello-cron
    
    # Apply cron job
    RUN crontab /etc/cron.d/hello-cron
    
    # Create the log file to be able to run tail
    RUN touch /var/log/hello-cron.log
    
    # Run the command on container startup
    CMD cron && tail -f /var/log/hello-cron.log
    

    This actually took me hours to figure out, as debugging cron jobs in docker containers is a tedious task. Hope it helps anyone else out there that can't get their code to work!

提交回复
热议问题