Search code examples
dockercrondockerfilecentos7

Running cron in Docker works but error all the time "/bin/sh: root: command not found"


I have the following Dockerfile:

FROM centos:7
RUN yum -y install crontabs
COPY --chmod=0644 dockerfiles/crontab /etc/cron.d/server-cron
RUN crontab /etc/cron.d/server-cron
RUN touch /var/log/cron.log
CMD crond && tail -f /var/log/cron.log

What is inside of the crontab file is as follows:

* * * * * root echo "Hello world" >> /var/log/cron.log 2>&1

When the container is up & running I can see the cron server working properly because the tail -f is printing Hello world to the console but is also printing the following error:

/bin/sh: root: command not found

I have searched on Google but nothing I have found is Docker-related:

(and many more)

Is there a way to get rid of this error while in a Docker container or I just should ignore it and leave it alone?


Solution

  • TLDR; Remove this line from your Dockerfile:

    RUN crontab /etc/cron.d/server-cron
    

    Longer explanation:

    You are essentially trying to run the cronjob twice.

    When this is run the Dockerfile, you are adding a system cronjob, since crond will run whatever is defined in that directory:

    COPY --chmod=0644 dockerfiles/crontab /etc/cron.d/server-cron
    

    When this is run the Dockerfile, you are creating a user cronjob:

    RUN crontab /etc/cron.d/server-cron
    

    So what you're seeing is the second cronjob (the one loaded by crontab) fail. As explained in the first link you posted. Cronjobs loaded with crontab have a different format and should not have the user defined (they are always run as the user that created it).

    But then you're also seeing the first cronjob (the file defined under /etc/cron.d) succeed because it is in the correct format, that defines the user.