Run Cron jobs inside Docker container
This Dockerfile can be used to execute python code, scheduled by a Cron job.
The basic steps followed, load a random python application which is executed from the index.py file.
Make sure cron is installed in the image, load environment variables into a env file, specifically created to load the environment variables (restrict unix permissions) needed by the python app, availabe to os.environ()
.
The python app start command is written into an executable file script.sh, whose execution will be finally scheduled by cron.
FROM python:3.8.12-slim-buster | |
RUN apt update && apt install -y cron vim | |
RUN mkdir /code | |
ARG DB_HOST | |
ARG DB_NAME | |
ARG DB_USER | |
ARG DB_PASS | |
ARG CRON_SCHEDULE | |
ENV DB_HOST=${DB_HOST} | |
ENV DB_NAME=${DB_NAME} | |
ENV DB_USER=${DB_USER} | |
ENV DB_PASS=${DB_PASS} | |
ENV CRON_SCHEDULE=${CRON_SCHEDULE:-"* * * * *"} | |
COPY ./app /code/app | |
COPY index.py /code/ | |
WORKDIR /code | |
RUN touch .myenv | |
RUN echo "export DB_HOST=${DB_HOST_REMOTE}" >> .myenv | |
RUN echo "export DB_PASS=\"${DB_PASS_REMOTE}\"" >> .myenv | |
RUN echo "export DB_USER=${DB_USER_REMOTE}" >> .myenv | |
RUN echo "export DB_NAME=${DB_NAME_REMOTE}" >> .myenv | |
RUN echo "source /code/.myenv" > load.sh && chmod +x load.sh | |
RUN echo "python /code/index.py >> /code/cron.log 2>&1 &" > script.sh | |
RUN chmod +x script.sh | |
RUN touch cron.log && chmod 664 cron.log | |
RUN crontab -l | { cat; echo "PATH=/bin/:/usr/bin:/usr/local/bin:$PATH\n\n\ | |
${CRON_SCHEDULE} BASH_ENV=/code/load.sh bash /code/script.sh\n\ | |
"; } | crontab - | |
CMD /etc/init.d/cron start && echo "Listening log..." && tail -f /code/cron.log |
The BASH_ENV
environment variable can be used to preload environment variables at the cronjob context.
Environment varaibles loaded with BASH_ENV are only available to the cron job loading the BASH_ENV
variable. In fact, entries in the crontab won’t share the same cron job context.