我正在尝试在调用 shell 脚本的 docker 容器中运行 cronjob。
昨天我一直在网上搜索和堆栈溢出,但我找不到真正有效的解决方案。
我怎样才能做到这一点?
编辑:
我创建了一个 (commented) github repository使用可在给定时间间隔调用 shell 脚本的工作 docker cron 容器。
最佳答案
您可以将您的 crontab 复制到一个镜像中,以便从该镜像启动的容器运行该作业。
见“Run a cron job with Docker”来自 Julien Boulay在他的 Ekito/docker-cron
:
Let’s create a new file called "
hello-cron
" to describe our job.
* * * * * 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.
如果你想知道什么是 2>&1,Ayman Hourieh explains .The following Dockerfile describes all the steps to build your image
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
(参见 Gaafar 的 comment 和 How do I make apt-get
install less noisy? :apt-get -y install -qq --force-yes cron
也可以工作)正如 Nathan Lloyd 所指出的在 the comments :
Quick note about a gotcha:
If you're adding a script file and telling cron to run it, remember to
RUN chmod 0744 /the_script
Cron fails silently if you forget.
或者,确保您的作业本身直接重定向到 stdout/stderr 而不是日志文件,如 hugoShaka 中所述的 answer :
* * * * * root echo hello > /proc/1/fd/1 2>/proc/1/fd/2
将最后一行 Dockerfile 替换为CMD ["cron", "-f"]
另见(关于 cron -f
,即 cron “前景”)“docker ubuntu cron -f
is not working ”构建并运行它:
sudo docker build --rm -t ekito/cron-example .
sudo docker run -t -i ekito/cron-example
Be patient, wait for 2 minutes and your commandline should display:
Hello world
Hello world
Eric添加 in the comments :
Do note that
tail
may not display the correct file if it is created during image build.
If that is the case, you need to create or touch the file during container runtime in order for tail to pick up the correct file.
参见“Output of
tail -f
at the end of a docker CMD
is not showing”。在“Running Cron in Docker”(2021 年 4 月)中查看更多信息,来自 Jason Kulatunga ,如他 commented below
查看 Jason 的图片
AnalogJ/docker-cron
基于:cronie
/crond
,取决于分布。/etc/environment
然后打电话cron -f -l 2
关于docker - 如何在 docker 容器内运行 cron 作业?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51431604/