【问题标题】:How do I get schedule:run to work with systemd in a docker container?如何让 schedule:run 在 docker 容器中使用 systemd?
【发布时间】:2018-08-26 04:21:57
【问题描述】:

按照this guide我设置了两个文件

/etc/systemd/system/lumen-cron.service

[Unit]
Description=Run lumen cron tasks
After=network.target

[Service]
User=root
ExecStart=/usr/bin/php /var/www/web/artisan schedule:run

/etc/systemd/system/lumen-cron.timer

[Unit]
Description=Run lumen timed tasks

[Timer]
OnBootSec=1min
OnUnitActiveSec=1m

[Install]
WantedBy=timers.target

我得到了我的 docker 镜像 FROM ubuntu:xenial 并且我的启动脚本有 systemctl enable lumen-cron

如果我登录到容器但调度程序没有运行。

$ journalctl -f -u lumen-cron.timer
No journal files were found.

$ journalctl -f -u lumen-cron.service
No journal files were found.

$ systemctl list-timers
Failed to connect to bus: No such file or directory

我碰壁了,我觉得我很接近了。有没有其他人通过 systemd 在 docker 容器中成功运行 laravel/lumen 调度程序?

【问题讨论】:

  • 您是在容器内设置这些文件对吗?顺便说一句,最好使用主机系统的 cron 在容器内运行计划任务。

标签: docker laravel-5 ubuntu-16.04 lumen systemd


【解决方案1】:

您似乎正在尝试在 Docker 容器内设置 systemd 单元。虽然可以在容器内使用systemd,但这并不是一种非常常见的设置。

如果您查看上面systemctl list-timers 的输出,您会注意到它与Failed to connect to bus: No such file or directory 出错。您可能会收到此错误,因为您尝试在 systemd 未运行的容器内使用 systemctl

那么,为什么 systemd 不在容器中运行?默认情况下,容器以多种方式与主机隔离。它们有自己的内核命名空间,包括自己的 PID 1。因此,默认情况下,您的容器将无法使用主机的 systemd 套接字。

为了在容器中使用systemd,您需要运行systemd 作为容器的PID 1。这意味着您有两个systemd 实例,一个在主机上,一个在容器中. RedHat 有一些 blog posts 介绍了如何使用 Fedora 映像来实现这一点,但是,正如您会注意到的,它需要一些特别的注意,而且它可能会超出您的需要。

相反,这里有一些可能会有所帮助的选项:

使用宿主的systemd:

这可能是最简单的解决方案。您可以将这些单元文件放在主机中,并更改 ExecStart= 行,以便它使用相同的命令启动一个新容器:

[Unit]
Description=Run lumen cron tasks
After=network.target

[Service]
Type=oneshot
ExecStart=/bin/docker run --rm -name lumen-cron yourdockerimage /usr/bin/php /var/www/web/artisan schedule:run

使用容器编排平台:

如果您有时间/资源来管理集群,那么使用诸如Kubernetes 之类的平台将是理想的选择,特别是如果您希望稍后将其扩展到多台服务器。

Kubernetes 的最新版本增加了对 CronJob 对象的支持,允许您指定定期运行的容器:

apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: lumen-cron
spec:
  schedule: "*/1 * * * *"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: lumen-cron
            image: yourimage
            args:
            - /usr/bin/php
            - /var/www/web/artisan
            - schedule:run
          restartPolicy: OnFailure

使用supervisord:

如果您只想在单个容器中运行所有内容,您可以在容器中使用 supervisord 作为 PID 1,并让它同时运行您的 PHP/webserver 和 crond

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-03
    • 2018-09-29
    • 2018-11-22
    相关资源
    最近更新 更多