我在尝试使cron作业在docker容器中运行时遇到的几个问题是:
- Docker容器中的时间不是UTC的本地时间;
- docker环境未传递给cron;
- 正如Thomas所指出的那样,cron日志记录还有很多不足之处,通过docker访问它需要基于docker的解决方案。
列表中存在特定于cron的问题和特定于docker的问题,但是无论如何都必须解决它们以使cron正常工作。
为此,我目前对问题提出的解决方案如下:
创建一个docker卷,在cron下运行的所有脚本都将写入其中:
# Dockerfile for test-logs# BUILD-USING: docker build -t test-logs .# RUN-USING: docker run -d -v /t-logs --name t-logs test-logs# INSPECT-USING: docker run -t -i --volumes-from t-logs ubuntu:latest /bin/bashFROM stackbrew/busybox:latest# Create logs volumeVOLUME /var/logCMD ["true"]
将在cron下运行的脚本是
test.py:
#!/usr/bin/env python# python script which needs an environment variable and runs as a cron jobimport datetimeimport ostest_environ = os.environ["TEST_ENV"]print "Cron job has run at %s with environment variable '%s'" %(datetime.datetime.now(), test_environ)
为了将环境变量传递给,我想在cron下运行,遵循托马斯的建议,并把一个crontab片段为每个脚本(或脚本组)的脚本,在需要的泊坞窗环境变量的
/etc/cron.d一个占位符
XXXXXXX,必须被设置。
# placed in /etc/cron.d # TEST_ENV is an docker environment variable that the script test.py needTEST_ENV=XXXXXXX#* * * * * root python /test.py >> /var/log/test.log
除了直接调用cron之外,还可以将cron包装在执行以下操作的python脚本中:1.从docker环境变量读取环境变量,并将环境变量设置为crontab片段。
#!/usr/bin/env python# run-cron.py# sets environment variable crontab fragments and runs cronimport osfrom subprocess import callimport fileinput# read docker environment variables and set them in the appropriate crontab fragmentenvironment_variable = os.environ["TEST_ENV"]for line in fileinput.input("/etc/cron.d/cron-python",inplace=1): print line.replace("XXXXXXX", environment_variable)args = ["cron","-f", "-L 15"]call(args)该
Dockerfile说的容器,其中cron作业运行如下:
# BUILD-USING: docker build -t test-cron .# RUN-USING docker run --detach=true --volumes-from t-logs --name t-cron test-cronFROM debian:wheezy## Set correct environment variables.ENV HOME /rootENV TEST_ENV test-valueRUN apt-get update && apt-get install -y software-properties-common python-software-properties && apt-get update# Install Python SetuptoolsRUN apt-get install -y python cronRUN apt-get purge -y python-software-properties software-properties-common && apt-get clean -y && apt-get autoclean -y && apt-get autoremove -y && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*ADD cron-python /etc/cron.d/ADD test.py /ADD run-cron.py /RUN chmod a+x test.py run-cron.py# Set the time zone to the local time zoneRUN echo "America/New_York" > /etc/timezone && dpkg-reconfigure --frontend noninteractive tzdataCMD ["/run-cron.py"]
最后,创建容器并运行它们:
- 创建日志卷(测试日志)容器:
docker build -t test-logs .
- 运行日志量:
docker run -d -v /t-logs --name t-logs test-logs
- 创建cron容器:
docker build -t test-cron .
- 运行cron容器:
docker run --detach=true --volumes-from t-logs --name t-cron test-cron
- 要检查在cron下运行脚本的日志文件:
docker run -t -i --volumes-from t-logs ubuntu:latest /bin/bash
。日志文件在中/var/log
。



