我正在使用 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
运行.sh
#!/bin/bash
crontab theservice-cron
cron -f
docker-compose.yml
version: '3.7'
services:
theservice:
build: .
env_file:
- ./.env
服务计划
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
我假设 cronjob 在另一个目录中运行,并且无法访问 /home/me/theservice/.env
中设置的环境变量。所以我尝试在 theservice-cron
文件中添加 HOME=/home/me/theservice
行,或者只是执行 /home/me/theservice
在运行脚本之前但它没有帮助。
在python脚本中,我使用os
访问环境变量
import os
print(os.environ['db_host'])
我该如何解决这个问题?
最佳答案
我有类似的问题。
我确实使用以下方法修复了它:
CMD printenv > /etc/environment && cron && tail -f /var/log/theservice-cron.log
根据 https://askubuntu.com/questions/700107/why-do-variables-set-in-my-etc-environment-show-up-in-my-cron-environment , cron 从/etc/enviroment 读取环境变量
关于python - 在 Docker 中运行 python cronjob 时缺少环境变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65884276/