如何在Docker容器中运行Cron作业?

发布于 2021-02-01 13:10:45

我正在尝试在调用shell脚本的docker容器中运行cronjob。

昨天我一直在网上搜索和堆栈溢出,但是我找不到真正可行的解决方案。
我怎样才能做到这一点?

编辑:

我已经创建了一个(带注释的)github存储库,上面有一个工作的docker cron容器,该容器以给定的时间间隔调用shell脚本。

关注者
0
被浏览
233
1 个回答
  • 面试哥
    面试哥 2021-02-01
    为面试而生,有面试问题,就找面试哥。

    您可以将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: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
    

    正如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 world
    Hello world
    

    Eric在评论中添加:

    请注意,tail如果在映像构建过程中创建了正确的文件,则可能无法显示正确的文件。
    在这种情况下,您需要在容器运行时创建或触摸文件,以便尾部拾取正确的文件。



推荐阅读
知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看