docker使用crontab运行python脚本
项目结构
└───file
│ └───*.py (一些python脚本
│
│
└───Dockerfile (制作docker镜像文件
│
│
└───requirements.txt (脚本中需要的包
│
│
└───root (crontab配置
│
│
└───docker-compose.yaml
dockerfile文件
- 根据制作可以crontab的镜像,基于python
FROM python:latest
RUN apt-get update && apt-get install -y cron
RUN apt-get install -y vim
COPY ./requirements.txt /requirements.txt
RUN pip install -i https://pypi.tuna.tsinghua.edu.cn/simple -r /requirements.txt
CMD ["cron", "-f"]
- 制作镜像
docker build -t test:v2 .
- 制作完成之后查看镜像是否存在
docker images
docker-compose.yaml 文件
version: "3"
services:
TEST:
image: test_v2
volumes:
- ./file/weather_service_API:/weather_service_API
- ./root:/var/spool/cron/crontabs/root
command: ["cron", "-f"]
user: root
# privileged: true
restart: always
root 文件
# DO NOT EDIT THIS FILE - edit the master and reinstall.
# (/tmp/crontab.JeaR4e/crontab installed on Sun Apr 18 07:02:47 2021)
# (Cron version -- $Id: crontab.c,v 2.13 1994/01/17 03:20:37 vixie Exp $)
# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h dom mon dow command
* * * * * echo "Hello world" >> /var/log/cron.log 2>&1 # 每分钟输出一次 hellow world 打印至/var/log/cron.log
* * * * * python /weather_service_API/test.py >> /var/log/cron.log 2>&1