在容器中运行 cron

voy*_*ech 4 php cron docker

我有一个托管 Symfony Web 应用程序的 php 容器。我需要使用后台脚本并从 crontab 启动它们。而且只要我使用 root 用户,它似乎就可以工作。但是,当我将用户切换到“www-data”时 - 它停止工作。我的想法是以用户 www-data 身份运行 php-fpm,并在进入容器时登录“www-data”。但是 crontab 可以为 root 用户定义,因为它允许在命令前加上用户名。

我的入口点文件包含:

#!/bin/bash
npm install
cron &
php-fpm
Run Code Online (Sandbox Code Playgroud)

我的 docker 文件如下所示:

WORKDIR /app

ADD ./entrypoint.sh /entrypoint.sh
RUN chmod 777 /entrypoint.sh

ADD ./crontab.txt /etc/cron.d/hello-cron
RUN chmod 0666 /etc/cron.d/hello-cron
RUN crontab /etc/cron.d/hello-cron
RUN touch /var/log/cron.log

RUN usermod -s /bin/bash www-data

USER www-data
ENTRYPOINT /entrypoint.sh
Run Code Online (Sandbox Code Playgroud)

如果我跳过行,上面的方法就有效

USER www-data
Run Code Online (Sandbox Code Playgroud)

但我想首先启动 cron (针对 root),然后将默认容器用户切换到 www-data...所以我也尝试过:

ENTRYPOINT /entrypoint.sh
USER www-data
Run Code Online (Sandbox Code Playgroud)

但效果不太好。任何帮助将不胜感激 :)

don*_*ngi 6

我在这种情况下遇到的问题是,当您使用非特权用户运行容器时,由于无法访问 cron.pid 文件,您无法启动 cron。

因此,最好的解决方法是为 cron 二进制文件设置SUID,这将允许使用 www-data 用户以 root 权限运行它。您还应该确保将 cron 设置添加到正确的用户的 crontab 中。

您可以通过以下方式修改 Dockerfile:

WORKDIR /app

ADD ./entrypoint.sh /entrypoint.sh
RUN chmod 777 /entrypoint.sh

ADD ./crontab.txt /etc/cron.d/hello-cron
RUN crontab -u www-data /etc/cron.d/hello-cron  # <---- setting crontab for user www-data
RUN chmod u+s /usr/sbin/cron  # <---- setting setuid
RUN touch /var/log/cron.log

RUN usermod -s /bin/bash www-data

USER www-data
ENTRYPOINT /entrypoint.sh
Run Code Online (Sandbox Code Playgroud)

这应该可以正常工作。