KTB
KTB

Reputation: 1529

Dockerizin a python cronjob

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}

Upvotes: 1

Views: 1671

Answers (1)

CLNRMN
CLNRMN

Reputation: 1457

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?

Upvotes: 2

Related Questions