如何在 Docker 容器下运行 cronjob ?

当您想要安排计划任务,可以使用内置在 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

dockerfile 复制代码
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

dockerfile 复制代码
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

dockerfile 复制代码
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 容器下正常运行。

我的开源项目

相关推荐
云飞云共享云桌面17 小时前
传统工作站 vs 云飞云共享云桌面:制造业设计云桌面选型深度对比
运维·服务器·前端·网络·3d·架构·制造
Hadoop_Liang18 小时前
使用Kubernetes Gateway API实现域名访问应用
容器·kubernetes·gateway
Maynor99620 小时前
我用 Codex 给自己的网站上线了一个智能体客服:从 Dify 到服务器部署,全程实战复盘
运维·服务器
java_cj21 小时前
深入kubectl create源码:从YAML到Pod的完整链路拆解
运维·云原生·容器·kubernetes
深圳恒讯1 天前
越南服务器BGP多线和单线有什么区别?
运维·服务器
志栋智能1 天前
超自动化运维如何提升安全合规水平?
运维·安全·自动化
A_humble_scholar1 天前
Linux(九) 进程管理完全指南:从入门到实战
linux·运维·chrome
江华森1 天前
Linux 操作命令完全指南
linux·运维
源图客1 天前
【AI向量数据库】Weaviate介绍与部署
运维·docker·容器
用什么都重名1 天前
Git分支合并与远程服务器同步实战:保留关键配置文件
运维·服务器·git