在 docker 容器中執行 cron 作業:逐步指南
P粉914731066
P粉914731066 2023-10-10 18:54:39
0
2
489

我正在嘗試在呼叫 shell 腳本的 docker 容器內執行 cronjob。

昨天我一直在網路上搜尋和堆疊溢出,但我找不到真正有效的解決方案。

我怎樣才能做到這一點?

P粉914731066
P粉914731066

全部回覆(2)
P粉563831052

接受的答案在生產環境中可能是危險的

當您使用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"]

#但是:如果你想執行任務 作為非根用戶

P粉818125805

您可以將 crontab 複製到映像中,以便從該映像啟動的容器執行該作業。


重要:如docker-cron 問題 3:對 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 CMD」末端的 tail -f”末尾的 輸出> 未顯示」。


請參閱「

在Docker 中執行Cron」以了解更多資訊(2021 年4 月)來自Jason Kulatunga,因為他評論如下

檢視 Jason 的映像 AnalogJ/docker-cron 基於:

  • Dockerfile 安裝 cronie/crond,取決於發行版。

  • 入口點初始化/etc/environment然後呼叫

    cron -f -l 2
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!