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

我的开源项目

相关推荐
STDD9 小时前
cert-manager:Kubernetes 自动 TLS 证书管理
云原生·容器·kubernetes
LN花开富贵11 小时前
Ubuntu aarch64 架构安装 NoMachine 远程控制 避坑与实战
linux·运维·笔记·学习·ubuntu·嵌入式
杨云龙UP11 小时前
Oracle RAC/ODA环境下如何准确查询PDB表空间已分配大小?一次说清Oracle表空间逻辑大小和ASM三副本实际占用_2026-05-19
linux·运维·数据库·sql·oracle·ffmpeg
码点滴12 小时前
K8s配置与存储运维自动化:从隐形杀手到 AI Agent 安全闭环
运维·人工智能·自动化
步十人12 小时前
【Linux】环境配置
linux·运维·服务器
念恒1230612 小时前
MySQl安装
linux·运维·服务器
卧室小白12 小时前
docker容器
运维·docker·容器
Benszen12 小时前
Docker容器化解决方案
运维·docker·容器
vortex512 小时前
现代 Linux 包管理全景:从 apt 到 Nix,四大派系与四大范式
linux·运维·服务器
曦夜日长12 小时前
Linux系统篇,开发工具(四):make及makefile的使用、makefile的使用细节
linux·运维·服务器