all

如何在 docker 容器中运行 cron 作业?

发布于 2022-03-22 22:40:17

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

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

关注者
0
被浏览
34
1 个回答
  • 面试哥
    面试哥 2022-03-22
    为面试而生,有面试问题,就找面试哥。

    您可以将 crontab 复制到映像中,以便从所述映像启动的容器运行作业。

    请参阅Julien Boulay的“使用 Docker 运行 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.
    

    如果您想知道什么是 2>&1, 解释说。

    以下 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
    

    正如指出的那样:

    关于一个陷阱的快速说明:
    如果您要添加一个脚本文件并告诉 cron 运行它,请记住 如果您忘记了 Cron 会静默失败
    RUN chmod 0744 /the_script



    或者,确保您的工作本身直接重定向到 stdout/stderr
    而不是日志文件,如下所述:

     * * * * * root echo hello > /proc/1/fd/1 2>/proc/1/fd/2
    

    将最后 Dockerfile 行替换为

    CMD ["cron", "-f"]
    

    构建并运行它:

    sudo docker build --rm -t ekito/cron-example .
    sudo docker run -t -i ekito/cron-example
    

    请耐心等待 2 分钟,您的命令行应该会显示:

    Hello world
    Hello world
    

    补道:

    请注意,tail如果在映像构建期间创建文件,可能不会显示正确的文件。
    如果是这种情况,您需要在容器运行时创建或触摸文件,以便 tail 获取正确的文件。


    AnalogJ/docker-cron请参阅基于以下内容的
    Jason 的图像:

    • Dockerfile 安装cronie/ crond,取决于发行版。

    • 一个入口点初始化/etc/environment然后调用

      cron -f -l 2
      


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

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

去下载看看