关于docker:容器中运行定时任务

13次阅读

共计 1023 个字符,预计需要花费 3 分钟才能阅读完成。

容器中运行定时工作

背景

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

思路

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

操作

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

    #!/bin/bash
    echo "$(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:3
    
    WORKDIR /usr/src/app
    
    # 装置依赖
    COPY . .
    RUN pip install --no-cache-dir -r requirements.txt
    
    # Install Pip
    RUN apt update
    RUN apt install -y cron
    
    # 设置定时脚本权限
    RUN chmod +x submit.sh
    
    # Add crontab file in the cron directory
    ADD cronfile /etc/cron.d/submit-cron
    
    # Give execution rights on the cron job
    RUN chmod 0644 /etc/cron.d/submit-cron
    
    # Create the log file to be able to run tail
    RUN touch /var/log/cron.log
    # 更改时区
    RUN rm -rf /etc/localtime
    RUN ln -s /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
    # Run the command on container startup
    CMD cron && tail -f /var/log/cron.log
    • 外围步骤:

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

参考

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