您可以将crontab复制到映像中,以使从该映像启动的容器运行该作业。
请参阅“ 运行与码头工人cron作业从”
朱利安·布雷他 Ekito/docker-cron
:
让我们创建一个名为“
hello-cron” 的新文件来描述我们的工作。
* * * * * 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.
以下Dockerfile描述了构建映像的所有步骤
FROM ubuntu:latestMAINTAINER docker@ekito.frRUN apt-get update && apt-get -y install cron# Copy hello-cron file to the cron.d directoryCOPY hello-cron /etc/cron.d/hello-cron# Give execution rights on the cron jobRUN chmod 0644 /etc/cron.d/hello-cron# Apply cron jobRUN crontab /etc/cron.d/hello-cron# Create the log file to be able to run tailRUN touch /var/log/cron.log# Run the command on container startupCMD cron && tail -f /var/log/cron.log
正如Nathan Lloyd在评论中指出的:
关于陷阱的快速说明:
如果要添加脚本文件并告诉cron运行它,请记住, 如果您忘记 了 Cron会静默失败 。RUN chmod 0744 /the_script
或者,确保您的工作本身直接重定向到stdout /stderr而不是日志文件,如hugoShaka:
* * * * * root echo hello > /proc/1/fd/1 2>/proc/1/fd/2
将最后一个Dockerfile行替换为
CMD ["cron", "-f"]
另请参阅(关于
cron -f,即cron“前景”)“ docker ubuntu
cron-f无法正常工作 ”
生成并运行它:
sudo docker build --rm -t ekito/cron-example .sudo docker run -t -i ekito/cron-example
请耐心等待2分钟,您的命令行应显示:
Hello worldHello world
Eric在评论中添加:
请注意,
tail如果在映像构建过程中创建了正确的文件,则可能无法显示正确的文件。
在这种情况下,您需要在容器运行时创建或触摸文件,以便尾部拾取正确的文件。



