Accepted Answer Can be dangerous in a production environment.
When you use CMD cron && tail -f /var/log/cron.log, the cron process basically forks to execute cron in the background and the main process exits And let you execute tailf in the foreground. The background cron process may stop or fail without you noticing, your container will still run silently, and your orchestration tool will not restart it.
Using basic shell redirection, you may want to do the following:
# must be ended with a new line "LF" (Unix) and not "CRLF" (Windows)
* * * * * echo "Hello world" >> /var/log/cron.log 2>&1
# An empty line is required at the end of this file for a valid cron file.
FROM ubuntu:latest
MAINTAINER docker@ekito.fr
RUN apt-get update && apt-get -y install cron
# Copy hello-cron file to the cron.d directory
COPY hello-cron /etc/cron.d/hello-cron
# Give execution rights on the cron job
RUN chmod 0644 /etc/cron.d/hello-cron
# Apply cron job
RUN crontab /etc/cron.d/hello-cron
# Create the log file to be able to run tail
RUN touch /var/log/cron.log
# Run the command on container startup
CMD cron && tail -f /var/log/cron.log
Accepted Answer Can be dangerous in a production environment.
When you use
CMD cron && tail -f /var/log/cron.log
, the cron process basically forks to executecron
in the background and the main process exits And let you executetailf
in the foreground. The background cron process may stop or fail without you noticing, your container will still run silently, and your orchestration tool will not restart it.Using basic shell redirection, you may want to do the following:
Your CMD will be:
CMD ["cron", "-f"]
However: If you want to run the task as a non-root user .
You can copy
crontab
into an image so that containers launched from that image run the job.IMPORTANT: Like docker-cron issue 3: Use
LF instead of CRLF
for cron files.SeeRunning cron jobs using Docker” /github.com/julienboulay" rel="noreferrer">Julien Boulay in his Ekito/docker -cron:
If you're wondering what
2>&1
is, Ayman Hourieh explains.But: If
cron
dies, containercontinues to run.(See Gaafar's comments and How to make
apt-get
install less noisy? :apt-get -y install -qq --force-yes cron
also works)As Nathan Lloyd commented on :
Alternatively, ensure that your job itself redirects directly to stdout/stderr rather than a log file, as hugoShaka answer :
Replace the last Dockerfile line with
However: If you want to run the task as a non-root user .
See also (about
cron -f
, the cron "frontend") "docker ubuntucron -f
does not work "Build and run it:
Eric added in comments:
See tail -f
output > not shown
”末尾的" at the end of "
docker CMD".See "Running Cron in Docker" for more information (April 2021) by Jason Kulatunga, Because his comments are as follows
View Jason's image
AnalogJ/docker-cron
Based on:Dockerfile installs
cronie
/crond
, depending on the distribution.Entry point initialization
/etc/environment
Then call