在 Docker 中运行 python cronjob 时缺少环境变量

mic*_*obg 4 python cron environment-variables docker docker-compose

我正在使用 crontab 在 docker 容器内运行 python 脚本。.env另外,我在项目目录中的文件中设置了一些环境变量(如数据库主机、密码等) 。如果我在容器 ( ) 内手动运行脚本,python3 main.py一切都会正常工作。但是当脚本通过 crontab 运行时,找不到环境变量 ( None)。我有以下设置:

Dockerfile

FROM ubuntu:latest

RUN apt-get update -y
RUN apt-get -y install cron
RUN apt-get install -y python3-pip python-dev

WORKDIR /home/me/theservice
COPY . .

RUN chmod 0644 theservice-cron
RUN touch /var/log/theservice-cron.log

RUN chmod +x run.sh

ENTRYPOINT ./run.sh
Run Code Online (Sandbox Code Playgroud)

运行sh

FROM ubuntu:latest

RUN apt-get update -y
RUN apt-get -y install cron
RUN apt-get install -y python3-pip python-dev

WORKDIR /home/me/theservice
COPY . .

RUN chmod 0644 theservice-cron
RUN touch /var/log/theservice-cron.log

RUN chmod +x run.sh

ENTRYPOINT ./run.sh
Run Code Online (Sandbox Code Playgroud)

docker-compose.yml

#!/bin/bash

crontab theservice-cron
cron -f
Run Code Online (Sandbox Code Playgroud)

服务-cron

version: '3.7'
services:
  theservice:
    build: .
    env_file:
      - ./.env
Run Code Online (Sandbox Code Playgroud)

我假设 cronjob 正在另一个目录中运行,并且其中设置的环境变量/home/me/theservice/.env不可访问。所以我尝试HOME=/home/me/theservicetheservice-cron文件中添加行或只是在运行脚本之前执行,/home/me/theservice但它没有帮助。

在python脚本中,我用来os访问环境变量

HOME=/home/me/theservice

* * * * * python3 /home/me/theservice/main.py >> /var/log/theservice-cron.log 2>&1
#* * * * * cd /home/me/theservice && python3 main.py >> /var/log/theservice-cron.log 2>&1

Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?

cri*_*tig 8

我有类似的问题。

我确实使用以下方法修复了它:

CMD printenv > /etc/environment && cron && tail -f /var/log/theservice-cron.log
Run Code Online (Sandbox Code Playgroud)

根据 https://askubuntu.com/questions/700107/why-do-variables-set-in-my-etc-environment-show-up-in-my-cron-environment, cron 从 /etc/ 读取环境变量环境