容器中運行定時任務
背景
- 想使用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中設置和修改時區