1

I am trying to schedule a task to run inside my container, but can't get cron to execute anything.

I've followed both How to run a cron job inside a docker container? and https://serverfault.com/questions/924779/docker-cron-not-working with no success. Simply nothing happens when I start up my container.

I have made a simple container:

test/
    Dockerfile
    hello-cron

Contents of Dockerfile:

FROM ubuntu:latest

RUN apt-get update && apt-get -y install cron

COPY hello-cron /etc/cron.d/hello-cron

RUN chmod 0644 /etc/cron.d/hello-cron

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

RUN touch /var/log/cron.log

CMD cron && tail -f /var/log/cron.log

and hello-cron:

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


I build my container: docker build -t cron-test . and run it docker run -t -i cron-test.

There is no console output. I have also tried to enter bash in the image to check the contents of the log-file and whether or not the hello-cron file is actually added to the crontab:

docker exec -it <image-id> bash

and cat /var/log/cron.log yields nothing, while the hello-cron file is located at /etc/cron.d/hello-cron.

I know this seems like a duplicate, but none of the accepted solutions I have seen solves this issue.

vegarab
  • 147
  • 2
  • 8

1 Answers1

4

I will suggest using alpine instead of ubuntu just for the sake of cron.

FROM alpine:latest

RUN echo "* * * * * echo hello;exit 0" | crontab - 
CMD ["crond","-f"]

you can explore more option

    -c  Crontab directory
    -u  User
    -l  List crontab
    -e  Edit crontab
    -r  Delete crontab
    FILE    Replace crontab by FILE ('-': stdin)

Also with alpine you do not need to make container good for no thing with CMD cron && tail -f /var/log/cron.log like you add in ubuntu base image.

When you use CMD like CMD cron && tail -f /var/log/cron.log , cron is no more the root process of the container and the container will restart or suppose to stop if cron is down.

using CMD ["crond","-f"] you will able to see logs in the console if you run the container in the foreground or you can checks logs latter.

Bonus:

You got working docker container for cronjob in just 5.58MB

Adiii
  • 54,482
  • 7
  • 145
  • 148