简体   繁体   English

Python Docker 容器中的 Cron 作业

[英]Python Cron Job in Docker Container

I have three files which is我有三个文件

  • crontab: lists of cron job to be execute crontab:要执行的 cron 作业列表

  • entrypoint.sh入口点.sh

     #!/usr/bin/env bash

    service cron start python服务 cron 启动 python

and docker file basically to install the pip and to run crontab on certain folder.和 docker 文件基本上是为了安装 pip 并在某些文件夹上运行 crontab。

My question is: Why in my docker container, the cron just start once and Exited.我的问题是:为什么在我的 docker 容器中,cron 只启动一次并退出。 have no ways to find the logs of it as it shows: Starting periodic command scheduler: cron.没有办法找到它的日志,因为它显示:启动定期命令调度程序:cron。

i wish to know whats the proper way of setting up and how to keep it running.我想知道什么是正确的设置方式以及如何保持运行。

Thanks谢谢

There are multiple ways on how you can run a cronjob inside a docker container.关于如何在 docker 容器中运行 cronjob 有多种方法。 Here is an example for a cron-setup on debian using cronjob files .这是使用cronjob 文件debian上进行 cron 设置的示例。

Create a crontab file创建一个 crontab 文件

  * * * * * root echo "Test my-cron" > /proc/1/fd/1 2>/proc/1/fd/2

my-cron - This file contains the interval , user and the command that should be scheduled. my-cron - 此文件包含间隔用户和应安排的命令 In this example we want to print the text Test my-cron every minute.在此示例中,我们希望每分钟打印一次文本Test my-cron

Create a docker entrypoint创建 docker 入口点

#!/usr/bin/env bash

cron                   # start cron service

tail -f /dev/null      # keep container running

entrypoint.sh - This is the entrypoint which gets executed when the container gets started. entrypoint.sh - 这是容器启动时执行的入口点。

Create a Dockerfile创建 Dockerfile

FROM debian:latest

RUN apt-get update \ 
    && apt-get install -y cron

# Cron file
ADD ./my-cron /etc/cron.d/my-cron
RUN chmod 0644 /etc/cron.d/my-cron

# Entrypoint
ADD ./entrypoint.sh /usr/bin/entrypoint.sh
RUN chmod +x /usr/bin/entrypoint.sh

CMD [ "entrypoint.sh" ]

Run

Build the image构建镜像

docker build . --tag my-cron

Start a container启动一个容器

docker run -d my-cron:latest

Check the console output检查控制台 output

docker logs <YOUR_CONTAINER_ID> --follow 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM