Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a cron job inside a docker container

Tags:

linux

docker

cron

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.

like image 934
V K Avatar asked May 03 '16 22:05

V K


People also ask

Can you run cron in Docker container?

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.

How do I run cron in foreground?

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 ).


2 Answers

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.

like image 140
Ken Cochrane Avatar answered Sep 17 '22 14:09

Ken Cochrane


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.

like image 20
Jarek Przygódzki Avatar answered Sep 20 '22 14:09

Jarek Przygódzki