如何在 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 容器下正常运行。

我的开源项目

相关推荐
考虑考虑5 小时前
docker compose环境变量替换
运维·后端·自动化运维
Java陈序员6 小时前
轻量运维面板!一款现代化的服务器控制面板工具!
运维·服务器·python·react.js·github
bosins6 小时前
WSL 迁移指南:如何将 Linux 环境完整复制到另一台电脑
linux·运维·服务器
IT利刃出鞘6 小时前
Docker Compose--安装WordPress--方法/示例
运维·docker·容器
handler018 小时前
【Linux】线程与虚拟内存的底层世界
linux·运维·服务器·c++·线程·虚拟地址空间·共享内存
新时代牛马8 小时前
实时 Linux:PREEMPT_RT、延迟来源与观测
linux·运维·服务器
zhexunnb9 小时前
深挖SAP系统模块价值,助力无锡制造企业打通数字化全链路
运维
weipt9 小时前
利用wsl给windows电脑上安装一个ubuntu
linux·运维·ubuntu
jarreyer9 小时前
【软件操作】加快资源管理器打开速度
运维
楚疏笃10 小时前
linux下给OpenCloudOS根目录扩容
linux·运维·服务器