0

I am trying to add cronjob and flask server in same docker image. My Dockerfile looks like this

FROM python:alpine3.9
RUN apk --update add build-base libffi-dev openssl-dev curl
ADD crontab.txt /crontab.txt
ADD cronscript.sh /cronscript.sh
COPY entry.sh /entry.sh
RUN chmod 755 /cronscript.sh /entry.sh
RUN /usr/bin/crontab /crontab.txt
RUN /bin/sh /entry.sh
WORKDIR /
RUN mkdir app
COPY requirements.txt /app
RUN pip install -r /app/requirements.txt
COPY *.py /app/
WORKDIR /app
RUN chmod +x main.py
ENTRYPOINT [ "python" ]
CMD [ "main.py" ]

cronscript.sh

#!/bin/sh
echo "Starting cronjob"
curl http://localhost:4000/health
echo "Completed cronjob"

crontab.txt

*/15 * * * * /cronscript.sh >> /var/log/cron.log

entry.sh

#!/bin/sh
# start cron
/usr/sbin/crond -l 2

This does not start cronjob. I see no data in /var/log/cron.log after waiting for an hour.

Where as if I move the line /bin/sh /entry.sh in my flask main function. Everything works.

flask main function

if __name__ == "__main__":
  os.system("/bin/sh /entry.sh")
  app.run(host='0.0.0.0', port=4000, debug=True)

Is there a way I can get this cron job working from Dockerfile itself and not python code? This feels like a hack.

Gaurav
  • 788
  • 2
  • 13
  • 27
  • Check out: https://stackoverflow.com/questions/37458287/how-to-run-a-cron-job-inside-a-docker-container – codedawi Feb 25 '21 at 23:22
  • 2
    It'll be easier to run two separate processes in two separate containers (they can be based on the same image). The `ENTRYPOINT` you have doesn't make sense, though, and makes this harder; write a single `CMD python main.py` (with no `ENTRYPOINT`) and you can separately `docker run your-image crond -f` overriding that command. – David Maze Feb 25 '21 at 23:28
  • @DavidMaze That should work. But I was checking if having cronjob with something else is at possible in single Dockerfile. – Gaurav Feb 26 '21 at 00:18

1 Answers1

0

You have to add extra line to make it cron valid. Please check (https://blog.knoldus.com/running-a-cron-job-in-docker-container/)

Mustafa Güler
  • 884
  • 6
  • 11