I succeeded to run my python code in a docker container when using CMD ["python3", "./mycode.py"].
Now, what I want is to run that python code every minute.
Dockerfile before(just run once):
FROM python:3.7
RUN apt-get update && \
apt-get install cron -y
RUN pip3 install requests
RUN head -n -1 /etc/ssl/openssl.cnf > /etc/ssl/temp && \
mv /etc/ssl/temp /etc/ssl/openssl.cnf
RUN echo "CipherString=DEFAULT@SECLEVEL=1" >> /etc/ssl/openssl.cnf
COPY . /app
WORKDIR /app
CMD ["python3", "./mycode.py"]
Dockerfile after(run every minute with crontab):
FROM python:3.7
RUN apt-get update && \
apt-get install cron -y
RUN pip3 install requests
RUN head -n -1 /etc/ssl/openssl.cnf > /etc/ssl/temp && \
mv /etc/ssl/temp /etc/ssl/openssl.cnf
RUN echo "CipherString=DEFAULT@SECLEVEL=1" >> /etc/ssl/openssl.cnf
RUN echo "* * * * * python /app/mycode.py" >> editcron && \
crontab editcron
COPY . /app
WORKDIR /app
CMD ["cron", "-f"]
But after building and running a new docker image with docker run -d --rm DockerImage, it doesn't seem to work.(And also, there is no cron log file at /var/log directory)
When I went into the container with docker exec -it DockerContainer /bin/bash, I could confirm that crontab -l prints "* * * * * python /app/mycode.py", and that python /app/mycode.py runs properly.
What could be a problem here?
I often keep crontab configuration in a separate file, it keeps Dockerfile clean and understandable,
Here is Working example that you can try
FROM python:3.6
RUN apt-get update && apt-get -y install cron vim
WORKDIR /app
COPY crontab /etc/cron.d/crontab
COPY hello.py /app/hello.py
RUN chmod 0644 /etc/cron.d/crontab
RUN /usr/bin/crontab /etc/cron.d/crontab
CMD ["cron", "-f"]
crontab config
#run python script every minutes
* * * * * python /app/hello.py > /proc/1/fd/1 2>/proc/1/fd/2
You can check complete working example in this Github Repo
docker-python-cronjob

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With