1

I have a python script which should run with python3. Now I have a requirement to run it as a cronjob. And then containerizing the whole package. Hence when installed, docker image should setup the cronjobs and run the python script in the docker.

I tried to execute the following, the build was successful and running it doesn't five any errors too. But it's not working.

What's the issue here?

requirements.txt

Flask
waitress

app.py

from datetime import datetime

print("\nThis is the cronjob running...:" , str(datetime.now()),"\n")

Dockerfile

FROM python:3-alpine

ENV PROJ_DIR="/app"
ENV CRON_SPEC="* * * * *"
ENV LOG_FILE="${PROJ_DIR}/app.log"

WORKDIR ${PROJ_DIR}

COPY . ${PROJ_DIR}

RUN pip install -r requirements.txt

CMD echo "${CRON_SPEC} python ${PROJ_DIR}/app.py >> ${LOG_FILE} 2>&1" > ${PROJ_DIR}/crontab

CMD crontab ${PROJ_DIR}/crontab

CMD crontab -l

CMD cron && tail -f ${LOG_FILE}
KTB
  • 1,499
  • 6
  • 27
  • 43

1 Answers1

2

As already mentioned, only the last CMD will be executed. You have to run your shell commands with RUN.

Here a working example of your Dockerfile with the required adjustments:

FROM python:3-alpine

ENV PROJ_DIR="/app"
ENV LOG_FILE="${PROJ_DIR}/app.log"
ENV CRON_SPEC="* * * * *" 

WORKDIR ${PROJ_DIR}

COPY . ${PROJ_DIR}

RUN pip install -r requirements.txt
RUN echo "${CRON_SPEC} python ${PROJ_DIR}/app.py >> ${LOG_FILE} 2>&1" > ${PROJ_DIR}/crontab
RUN touch ${LOG_FILE} # Needed for the tail
RUN crontab ${PROJ_DIR}/crontab
RUN crontab -l
CMD crond  && tail -f ${LOG_FILE} #crond runs per default in the background

Does this solve your problem?

CLNRMN
  • 1,409
  • 9
  • 23
  • yes it works now, i can see the docker running (docker ps). But now the problem is how to check the logs, to see the output of the, I ran docker logs -f , but id doesn't print the expected output. I wonder whether the python is not running. Is there a way to check the issue here? – KTB Apr 25 '20 at 12:01
  • How long did you wait? The cronjob with `* * * * *` is running every minute. I've checked also locally and I've got some logs. – CLNRMN Apr 25 '20 at 12:03
  • Thank you @CLNRMN, It works in the mac, the log shows the intended print. But when I ran the same Docker in the AWS Linux machine, it doesn't give any output. Is there a way to debug or any idea what could have gone wrong. – KTB Apr 25 '20 at 13:06
  • @KTB: I believe you need to install `cron` on the linux machine first. Check this if it could help: https://stackoverflow.com/questions/37458287/how-to-run-a-cron-job-inside-a-docker-container – Hai Nguyen Feb 16 '22 at 02:04