首页  >  问答  >  正文

在 docker 容器中执行 cron 作业:分步指南

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

昨天我一直在网上搜索和堆栈溢出,但我找不到真正有效的解决方案。

我怎样才能做到这一点?

P粉914731066P粉914731066345 天前490

全部回复(2)我来回复

  • P粉563831052

    P粉5638310522023-10-11 17:56:26

    接受的答案在生产环境中可能是危险的

    当您使用CMD cron && tail -f /var/log/cron.log时,cron进程基本上会分叉以便在后台执行cron,主进程退出并让您在前台执行 tailf 。后台 cron 进程可能会停止或失败,您不会注意到,您的容器仍将静默运行,并且您的编排工具不会重新启动它。

    使用基本的 shell 重定向,您可能想要执行如下操作:

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

    你的 CMD 将是:CMD ["cron", "-f"]

    但是:如果你想运行任务 作为非根用户

    回复
    0
  • P粉818125805

    P粉8181258052023-10-11 16:39:03

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


    重要:如docker-cron 问题 3< 中所述< /a>:对 cron 文件使用 LF,而不是 CRLF


    请参阅 使用 Docker 运行 cron 作业” /github.com/julienboulay" rel="noreferrer">Julien Boulay 在他的 <代码>Ekito/docker-cron

    # 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.

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

    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死亡,容器继续运行

    (请参阅 Gaafar评论如何让 apt-get 安装时噪音较小?
    apt-get -y install -qq --force-yes cron 也可以工作)

    正如 Nathan Lloyd评论


    或者,确保您的作业本身直接重定向到 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
    Hello world
    Hello world

    Eric 添加了在评论中

    请参阅“docker CMDtail -f 输出> 未显示”。


    请参阅“在 Docker 中运行 Cron”了解更多信息(2021 年 4 月)来自 Jason Kulatunga,因为他 评论如下

    查看 Jason 的图像 AnalogJ/docker-cron 基于:

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

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

      cron -f -l 2

    回复
    0
  • 取消回复