Search code examples
dockercroncontainerscron-task

Cron task inside container from host


I am trying a cron task inside a container from host but with no luck. From the host I am adding the following line on crontab -e

* * * * * docker exec -it sample_container bash -c 'touch /selected/directory/temp$(date +%H-%M)'

But this is not working. Interestingly, when I run the command independently outside crontab it is successfully executing. Can anyone explain what am I missing here?


Solution

  • Note: when debugging such problems with cron, you should look for errors in your local system mails or redirect those to your real mail by adding [email protected] on top of your crontab file.


    There are 2 problems with your crontab command

    TLDR; the fixed cron expression

    * * * * * docker exec sample_container bash -c 'touch /selected/directory/temp$(date +\%H-\%M)'
    

    % has a special meaning in crontab

    From man -s 5 crontab

    Percent-signs (%) in the command, unless escaped with backslash (\), will be changed into newline characters, and all data after the first % will be sent to the command as standard input.

    So you will need to escape those % signs in your date format string

    Cron does not allocate a tty

    Cron does not allocate a tty whereas your are trying to use one when executing your command (i.e. the -t option to docker exec). The command will therefore fail with the error the input device is not a TTY

    You do not need to go interactive (-i) nor to allocate a tty for this command to do its job anyway, so you have to drop those options to launch it from cron.