繁体   English   中英

在 Docker 容器中运行 bash 脚本作为 cron 作业

[英]Run a bash script as cron job in Docker container

我想在 Docker 容器内定期运行 bash 脚本(我的工作基于此答案: https://stackoverflow.com/240756585996/240746

这是我的脚本hello.sh


#!/bin/sh
echo "Hello world" >> /var/log/cron.log 2>&1

这是 cron 文件hello-cron

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

这是我的 Dockerfile:

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”。 如果我通过直接echo "Hello world" >> /var/log/cron.log 2>&1替换对 cron 文件中脚本的调用,它可以工作,我每分钟都会看到 "Hello world"

我究竟做错了什么?

编辑

Docker 命令:

docker build -t hello-cron .
docker run -t -i hello-cron

关于你的具体问题

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

尝试:

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

最佳实践

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

其次,请注意您的 cron.log 未安装,因此,如果 docker 重新启动,您将丢失此信息。

暂无
暂无

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

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