【发布时间】:2020-12-04 07:35:01
【问题描述】:
我想在 Docker 容器内定期运行一个 bash 脚本(我的工作基于这个答案:https://stackoverflow.com/a/37458519/6240756)
这是我的脚本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
【问题讨论】:
-
你能把你的
docker run指令输入一下吗? -
@mulg0r 查看编辑后的帖子
-
与此问题无关,但
cron已经知道/etc/cron.d中的文件;您不需要使用crontab命令安装它们。这个目录中的文件确实需要一个额外的字段(用户名),所以* * * * * * root /app/hello.sh。