容器中运行定时工作

背景

  • 想应用Docker容器中跑一个定时工作,于是有了本篇文章

思路

  • 通过查问,有的帖子倡议应用宿主机执行定时的docker exec命令,然而这样感觉应用Docker的意义就不大了,还是把定时工作放在容器中比拟好
  • 因而间接在容器中应用cron执行定时工作,然而这其中的坑比拟多,特此记录

操作

  • submit.sh 要定时执行的脚本

    #!/bin/bashecho "$(date): " >> /var/log/cron.log 2>&1/usr/local/bin/python /usr/src/app/submit_3chk.py >> /var/log/cron.log 2>&1
    • 留神在定时执行的脚本中的命令要应用绝对值指定可执行文件的地位
  • cronfile 定时工作配置文件

    13 8 * * * root /usr/src/app/submit.sh
    • cron工夫格局这里不再赘述
    • 每天的8:13应用root用户执行submit.sh脚本
  • Dockerfile

    FROM python:3WORKDIR /usr/src/app# 装置依赖COPY . .RUN pip install --no-cache-dir -r requirements.txt# Install PipRUN apt updateRUN apt install -y cron# 设置定时脚本权限RUN chmod +x submit.sh# Add crontab file in the cron directoryADD cronfile /etc/cron.d/submit-cron# Give execution rights on the cron jobRUN chmod 0644 /etc/cron.d/submit-cron# Create the log file to be able to run tailRUN touch /var/log/cron.log# 更改时区RUN rm -rf /etc/localtimeRUN ln -s /usr/share/zoneinfo/Asia/Shanghai /etc/localtime# Run the command on container startupCMD cron && tail -f /var/log/cron.log
    • 外围步骤:

      • 定时脚本要加可执行权限
      • 定时配置文件放到/etc/cron.d/目录下
      • 更改时区为Asia/Shanghai
      • 执行cron
  • 构建镜像后运行容器即可

参考

  • 在Docker中执行定时工作
  • Linux打印工夫
  • Linux中设置和批改时区