I tried to run a cron job inside a docker container but nothing works for me.
My container has only cron.daily
and cron.weekly
files.crontab,cron.d,cron.hourly
are absent in my container.crontab -e
is also not working.
My container runs with /bin/bash
.
One way to create scheduled tasks for your containers is by using the host's crontab. Since the definition of each cron job allows you to execute commands, you can use Docker Engine in the same way you would the command line.
When running cron as your ENTRYPOINT in a container, make sure you start cron in foreground mode ( cron -f ) and consider redirecting your job's stdout and stderr to crons (eg. */1 * * * * root /app1/test.sh > /proc/1/fd/1 2>/proc/1/fd/2 ).
Here is how I run one of my cron containers.
Dockerfile:
FROM alpine:3.3 ADD crontab.txt /crontab.txt ADD script.sh /script.sh COPY entry.sh /entry.sh RUN chmod 755 /script.sh /entry.sh RUN /usr/bin/crontab /crontab.txt CMD ["/entry.sh"]
crontab.txt
*/30 * * * * /script.sh >> /var/log/script.log
entry.sh
#!/bin/sh # start cron /usr/sbin/crond -f -l 8
script.sh
#!/bin/sh # code goes here. echo "This is a script, run by cron!"
Build like so
docker build -t mycron .
Run like so
docker run -d mycron
Add your own scripts and edit the crontab.txt and just build the image and run. Since it is based on alpine, the image is super small.
crond works well with tiny on Alpine
RUN apk add --no-cache tini ENTRYPOINT ["/sbin/tini", "--"] CMD ["/usr/sbin/crond", "-f"]
but should not be run as container main process (PID 1) because of zombie reaping problem and issues with signal handling. See this Docker PR and this blog post for details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With