在Docker容器中将bash脚本作为cron作业运行 关于您的具体问题最佳做法

问题描述

我想在Docker容器中定期运行bash脚本(我的工作基于以下答案:https://stackoverflow.com/a/37458519/6240756

这是我的脚本<a href="test.html"> test </a>

hello.sh

以下是cron文件 #!/bin/sh echo "Hello world" >> /var/log/cron.log 2>&1

hello-cron

这是我的Dockerfile:

# m h  dom mon dow   command
* * * * * /app/hello.sh
# Empty line

我构建并运行了容器,但没有任何反应。我应该每分钟看到一次“ Hello world”。 如果我将对cron文件中脚本的调用直接替换为FROM ubuntu:20.04 RUN apt-get update && apt-get install -y cron # Add backup script COPY hello.sh /app/ RUN chmod +x /app/hello.sh # Configure the cron # Copy file to the cron.d directory COPY hello-cron /etc/cron.d/hello-cron # Give execution rights on the cron job RUN chmod 0644 /etc/cron.d/hello-cron # Apply cron job RUN crontab /etc/cron.d/hello-cron # Create the log file to be able to run tail RUN touch /var/log/cron.log # Start the cron CMD cron && tail -f /var/log/cron.log 即可,那么我每分钟都会看到“ Hello world”

我在做什么错了?

编辑

以及Docker命令:

echo "Hello world" >> /var/log/cron.log 2>&1

解决方法

关于您的具体问题

问题是您正在使用-t -i启动docker,而您想要的是后台执行并进行交互检查。

尝试:

docker run -d --name mycontainer hello-cron 
docker logs -f mycontainer

最佳做法

如果您要定期执行某项操作,请考虑是否应在运行状况检查定义中进行设置,您可以在其中设置时间段和其他变量。

第二,请注意,您的cron.log未挂载,因此,如果docker restart,您将丢失此信息。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...