想要在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 docker@ekito.fr
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