Docker里crontab定时任务

想要在docker里执行crontab定时任务,最大的坑就是不执行定时任务,大体原因有以下:

  1.  时区不对,docker里的时区和我国差8个小时。cp 上海时区进docker 的/etc/localtime
  2. crond 服务没启动,Dockerfile的cmd一行需执行crond守护进程
  3. 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值