想要在docker裏執行crontab定時任務,最大的坑就是不執行定時任務,大體原因有以下:
- 時區不對,docker裏的時區和我國差8個小時。cp 上海時區進docker 的/etc/localtime
- crond 服務沒啓動,Dockerfile的cmd一行需執行crond守護進程
- crond 配置文件有問題
下面是本人親自嘗試正確的例子。創建一個文件夾放以下的東西
準備定時文件
定時文件後面請多帶一行空行
# hello-cron
* * * * * echo "Hello world" >> /var/log/cron.log 2>&1
crond配置文件
cp一份 /etc/pam.d/crond 文件,修改reques-->sufficient
#
# The PAM configuration file for the cron daemon
#
#
# No PAM authentication called, auth modules not needed
account sufficient pam_access.so
account include password-auth
session sufficient pam_loginuid.so
session include password-auth
auth include password-auth
時區文件
cp一份上海時區,以備後用
cp /usr/share/zoneinfo/Asia/Shanghai .
編寫Dockerfile文件
基礎鏡像自行修改,本人是使用自己本地的一個鏡像做的測試
FROM docker.registry.clouddev.sogou:5000/online/test-xzy:3
MAINTAINER [email protected]
RUN yum -y install crontabs
# Copy hello-cron file to the cron.d directory
COPY hello-cron /etc/cron.d/hello-cron
COPY crond /etc/pam.d/crond
COPY Shanghai /etc/localtime
# 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 crond && tail -f /var/log/cron.log
編譯出鏡像
docker build --rm -t xzy/cron-example .
啓動鏡像
docker run -t -i xzy/cron-example:latest
會看到每個一分鐘,終端打印 Hello world