在 Alpine Linux 容器中使用 Crontab

鳳凰卷大佬的 Planet.js 輪子非常有用,但是沒有做容器化。於是花了一個下午,簡單地寫了一個能用的 Dockerfile,並且順帶 PR 回了原項目。由於整個項目是基於 Node.js 的,因此打包也用了基於 Alpine Linux 的 node:alpine 容器。

爲了實現定時更新源,容器在執行入口指令稿的時候,需要設定好 Crontab,並且讓 Cron 執行起來。Alpine Linux 是一個輕量級的 Linux Distribution,所附帶的 Cron 也是使用了 Busybox 內建的 Cron 功能。看一下幫助大概更清楚一些:

/var/www # crond --help
BusyBox v1.28.4 (2018-07-17 15:21:40 UTC) multi-call binary.

Usage: crond -fbS -l N -d N -L LOGFILE -c DIR

    -f  Foreground
    -b  Background (default)
    -S  Log to syslog (default)
    -l N    Set log level. Most verbose:0, default:8
    -d N    Set log level, log to stderr
    -L FILE Log to FILE
    -c DIR  Cron dir. Default:/var/spool/cron/crontabs

可以發現預設的 Crontab 資料夾在 /var/spool/cron/crontabs,而在 Alpine Linux 下,它有一個軟連接在 /etc/crontabs。資料夾裏只有一個檔案,名爲 root,只要向裏面追加指令就可以完成設定了。

echo "${CRON_COMMAND}" >> /etc/crontabs/root

隨後,需要在入後指令稿內執行 crond,Cron 會自己跑到後臺執行並且完成定時任務。當然也可以讓 Cron 在前臺運行,並且作爲容器的守護行程:

crond -f

然後就能看到:

....
crond[21]: crond (busybox 1.28.4) started, log level 8
....
crond[21]: USER root pid  27 cmd su node -c planet
....

這樣就證明 Cron 任務正常執行了。接下來,合併 PR、設定 CD、推上 Docker Hub,一切就看鳳凰卷大佬的了。

17
1

Comments

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

To respond on your own website, enter the URL of your response which should contain a link to this post’s permalink URL. Your response will then appear (possibly after moderation) on this page. Want to update or remove your response? Update or delete your post and re-enter your post’s URL again. (Find out more about Webmentions.)