【问题标题】:Cron jobs show but are not executed in dockerized Django appCron 作业显示但未在 dockerized Django 应用程序中执行
【发布时间】:2021-07-05 21:02:51
【问题描述】:

我安装的应用中有“django_crontab”。

我配置了一个 cron 作业

CRONJOBS = [
    ('* * * * *', 'django.core.management.call_command',['dbbackup']),
]

我的 YAML 如下所示:

web:
    build: .
    command:
      - /bin/bash
      - -c
      - |
        python manage.py migrate
        python manage.py crontab add
        python manage.py runserver 0.0.0.0:8000

build + up 然后我打开 CLI:

$ python manage.py crontab show
Currently active jobs in crontab:
efa8dfc6d4b0cf6963932a5dc3726b23 -> ('* * * * *', 'django.core.management.call_command', ['dbbackup'])

那我试试:

$ python manage.py crontab run efa8dfc6d4b0cf6963932a5dc3726b23
Backing Up Database: postgres
Writing file to default-858b61d9ccb6-2021-07-05-084119.psql

一切都好,但 cronjob 永远不会被执行。我没有像预期的那样每分钟都看到新的数据库转储。

【问题讨论】:

  • 准确地说:$ crontab -l * * * * * /usr/local/bin/python /code/manage.py crontab run efa8dfc6d4b0cf6963932a5dc3726b23 # django-cronjobs for mysite

标签: django docker cron dump


【解决方案1】:

django-crontab 本身不运行预定的作业;它只是系统 cron 守护进程的一个包装器(例如,您需要使用 crontab(1) 的位置对其进行配置)。由于 Docker 容器只运行一个进程,因此您需要有第二个容器来运行 cron 守护进程。

我在这里可能推荐的设置是编写一些其他脚本来执行所有必需的启动时设置,然后运行一些可以作为附加参数传递的命令:

#!/bin/sh
# entrypoint.sh: runs as the main container process
# Gets passed the container's command as arguments

# Run database migrations.  (Should be safe, if inefficient, to run
# multiple times concurrently.)
python manage.py migrate

# Set up scheduled jobs, if this is the cron container.
python manage.py crontab add

# Run whatever command we got passed.
exec "$@"

然后在您的 Dockerfile 中,将此脚本设为 ENTRYPOINT。确保也提供默认的CMD,这可能会运行主服务器。两者都提供,Docker will pass the CMD as arguments to the ENTRYPOINT

# You probably already have a line like
# COPY . .
# which includes entrypoint.sh; it must be marked executable too

ENTRYPOINT ["./entrypoint.sh"] # must be JSON-array form
CMD python manage.py runserver 0.0.0.0:8000

现在在 docker-compose.yml 文件中,您可以提供来自同一个映像的两个容器,但只能覆盖 cron 容器的 command:。入口点脚本将为两者运行,但在其最后一行启动不同的命令。

version: '3.8'
services:
  web:
    build: .
    ports:
      - '8000:8000'
    # use the Dockerfile CMD, don't need a command: override
  cron:
    build: .
    command: crond -n # for Vixie cron; BusyBox uses "crond -f"
    # no ports:

【讨论】:

  • 感谢您的回答。我收到此错误消息:cron_1 | ./entrypoint.sh: 13: exec: crond: not found 然后 cron_1 以代码 127 退出
  • 我的 Dockerfile 以 FROM python:3.8.6-slim-buster 开头
  • 我已将“command:crond -n”替换为“command:cron”,我得到“cron:can't open or create /var/run/crond.pid: Permission denied”跨度>
  • 最后我得到了: - 创建了 David 提到的附加服务 - 使用特定的 Dockerfile 运行它(我在其中复制了我的 django 项目 + 一个 DB 转储脚本 + 添加了一个 cronjob )〜我得到了灵感来自stackoverflow.com/questions/37458287/… -
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-27
  • 2014-04-04
  • 1970-01-01
  • 1970-01-01
  • 2011-07-10
相关资源
最近更新 更多