
当您想要安排计划任务,可以使用内置在 macOS 和 Linux 中的常见工具,比如 cron,或者像 AWS Lambda 这样的特殊工具。Cron 不如 AWS Lambda 强大,但它在 Unix 系统的后台任务中工作得很好,特别是在使用容器的情况下。然而,对于 Docker 来说这有点复杂,因为不能简单地从终端开始新的 cron 作业,并期望它工作。
How to Dockerize a Cron Job
要在 Docker 容器中运行 cron 作业,您需要使用 cron 并在 Docker 容器的前台运行它。
下面是一个如何设置的例子:
Create Cron File
创建一个文件,其中包含要在 Docker 容器下运行的所有 cron 作业。
cat cron
我们的示例文件如下:
* * * * * echo "Current date is `date`" > /var/log/cron
Create Dockerfile
接下来,创建一个安装 cron 服务的 Dockerfile,并将脚本复制到容器。
在这里,我们提供了 3 个 Dockerfile 示例,它们使用不同的操作系统。
Dockerfile with Alpine Linux
FROM alpine:3
# Copy cron file to the container
COPY cron /etc/cron.d/cron
# Give the permission
RUN chmod 0644 /etc/cron.d/cron
# Add the cron job
RUN crontab /etc/cron.d/cron
# Link cron log file to stdout
RUN ln -s /dev/stdout /var/log/cron
# Run the cron service in the foreground
CMD [ "crond", "-l", "2", "-f" ]
Dockerfile with Apache and PHP
FROM php:8.0-apache
# Install cron
RUN apt update && \
apt -y install cron
# Copy cron file to the container
COPY cron /etc/cron.d/cron
# Give the permission
RUN chmod 0644 /etc/cron.d/cron
# Add the cron job
RUN crontab /etc/cron.d/cron
# Link cron log file to stdout
RUN ln -s /dev/stdout /var/log/cron
# Start cron service
RUN sed -i 's/^exec /service cron start\n\nexec /' /usr/local/bin/apache2-foreground
Dockerfile with Ubuntu Linux
FROM ubuntu:latest
# Install cron deamon
RUN apt update && apt install -y cron
# Copy cron file to the container
COPY cron /etc/cron.d/cron
# Give the permission
RUN chmod 0644 /etc/cron.d/cron
# Add the cron job
RUN crontab /etc/cron.d/cron
# Link cron log file to stdout
RUN ln -s /dev/stdout /var/log/cron
# Run the cron service in the foreground
CMD ["cron", "-f"]
Build and Run Container
当前目录中有两个文件,一个是 cron, 它包含了 cronjob。 一个是 Dockerfile, 它有 Docker 的构建指令。运行以下命令使用 Dockerfile 构建 Docker 镜像。
docker build -t my_cron .
镜像构建成功后,启动容器:
docker run -d my_cron
这将启动容器下的 cron 守护进程,它将执行 cron 文件中定义的所有计划作业。
Test Setup
我们已经链接了 cron 日志文件 /var/log/cron 到 /dev/stdout ,Cron 服务生成的所有日志
可以使用 docker logs 命令查看。
首先,使用 docker ps 命令查找容器 id 或名称。
docker ps
然后检查 Docker 容器的日志文件。
docker logs container_id
在 cronjobs 中,我打印了当前日期并把它们写入日志中。

输出如上所示,这意味着 cron 作业在 Docker 容器下正常运行。
