Docker:cron作业未运行

时间:2019-04-15 13:56:51

标签: docker cron

我正在尝试使cronjob在使用docker部署的项目上运行。我能够构建映像并成功运行容器,但是,当我登录到容器并检查/var/log时cron作业没有运行。

以下是文件:

Dockerfile

# use this image, as we'll need to run chron etc.
FROM phusion/baseimage:0.11

# Install python3, pip and cron
RUN apt-get update && \
    apt-get -y install cron python3 python3-pip && \
               pip3 install --upgrade pip

# Create required volumes
VOLUME /var/log   
VOLUME /srv/data

# Set environment
ENV TEST_ENV=/srv/data

COPY fetcher.py /fetcher.py

# Add crontab file in the cron directory
ADD crontab /etc/cron.d/cron-fetcher

# Give execution rights on the cron job
RUN chmod 0644 /etc/cron.d/cron-fetcher

# Create the log file to be able to run tail
RUN touch /var/log/cron.log

# Apply cron job
RUN crontab /etc/cron.d/cron-fetcher


# Run the command on container startup
CMD ["cron", "-f"]

crontab

# placed in /etc/cron.d 
* * * * * root python3 /fetcher.py >> /var/log/fetcher.log

fetcher.py

#!/usr/bin/env python

import urllib.request

# python script which needs an environment variable and runs as a cron job
import datetime
import os

test_environ = os.environ["TEST_ENV"]
print ("Cron job has run at {0} with environment variable '{1}'".format(datetime.datetime.now(), test_environ))
host_path = test_environ
url = 'http://winterolympicsmedals.com/medals.csv'
response = urllib.request.urlopen(url)
html = response.read()
filename = "{0}/data.csv".format(host_path)

with open(filename, 'wb') as f:
    f.write(html)

为什么cronjob没有运行?

1 个答案:

答案 0 :(得分:1)

/etc/cron.d中的文件需要指定用户:

# placed in /etc/cron.d 
* * * * * root python3 /fetcher.py >> /var/log/fetcher.log