使用dockerfile制作定时执行任务镜像

基于debian系统制作定时执行任务镜像。制作过程遇到几个难题:

1.怎么让docker运行时,crontab的服务是启动状态?

2.dockerfile的环境变量怎么传递给脚本使用?

3.怎样在crontab中添加定时任务?

所有的问题都在下面的这个dockerfile文件中解决了。

1.编写dockerfile文件:

FROM debian:10
​
ADD test.sh /opt/test.sh 
​
#获取cron下载资源列表
RUN sed -i '/jessie-updates/d' /etc/apt/sources.list  # Now archived
​
#cron下载
RUN apt-get update && apt-get -y install cron 
​
ADD stup.sh /etc/init.d/stup.sh 
​
#将启动cron的脚本放在/ect/init.d/目录下,开机自启动cron,ENTRYPOINT执行脚本
ENTRYPOINT ["./etc/init.d/stup.sh"]
​
#添加环境变量到容器内部的/etc/profile中,crontab无法识别dockefile中ENV设置的环境变量
RUN echo 'HELLO_WORLD="hello world" \nLIGHT_HOUSE="light house"  \nexport HELLO_WORLD \nexport LIGHT_HOUSE' >> /etc/profile
​
#为crontab添加定时任务,执行 . /etc/profile 使配置的环境变量生效
RUN echo '* * * * * . /etc/profile && /opt/test.sh >> /opt/test.log 2>&1 &' | crontab

2.编写cron启动脚本stup.sh:

#!/bin/bash
​
/etc/init.d/cron start
​
#将容器挂起,防止容器后台启动后自动退出
tail -f /dev/null

3.编写要执行的脚本内容,并输出到日志文件中:

#!/bin/bash
​
echo ${HELLO_WORLD} ${LIGHT_HOUSE}

4.构建镜像

扫描二维码关注公众号,回复: 16558042 查看本文章

docker build -t cron_test:0.1 .

5.启动docker容器

docker run -id --name crondt cron_test:0.1

6.进入容器(docker exec -it crond bash),查看cron服务运行状态(service cron status),查看设置的环境变量(cat etc/profile)

并查看定时任务输出的文件(cat opt/test.log),确认定时任务有执行(最好保证执行的脚本和输出日志都是绝对路径,不然定时任务可能无法执行)

--------------------------------------------------------分割线----------------------------------------------------------------

对于第一个问题,做点补充,镜像启动时,其实是运行的docker-entrypoint.sh脚本,运行命令

ENTRYPOINT ['docker-entrypoint.sh'],因为我已经在dockersfile里面设置了ENTRYPOINT这个命令,且这个命令是只生效一次且是覆盖,以最后一次为准。所以,还有一种方法是在本地编辑一个docker-entrypoint.sh,在脚本里面添加启动cron的命令(/etc/init.d/cron),替换docker里面的脚本,这样运行docker时也会启动crontab服务。

dockerfile:

ADD docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh

RUN chmod 760 /usr/local/bin/docker-entrypoint.sh

#注释掉
#ENTRYPOINT ["./etc/init.d/stup.sh"]

PS:把docker内部的docker-entrypoint.sh拷贝到本地,然后再添加启动命令。如果不这样操作可能会报错:warning: here-document at line 163 delimited by end-of-file (wanted `EOF')

猜你喜欢

转载自blog.csdn.net/Json_Marz/article/details/126000249