Issue
I have a Python script that is running in a docker container as a cron job, I would like to see the stdout in docker logs for example I have in my script the following line
print("BT: " + bt)
I would like to see this output when I am running docker logs some-container
my cron job as following
* * * * * root /usr/local/bin/python /opt/platform-location/platform-location.py >> /var/log/cron.log 2>&1
and I am running the cron
from Dockerfile as following:
FROM python:3
WORKDIR /opt/platform-location
COPY requirements.txt requirements.txt
COPY URLs.txt URLs.txt
COPY platform-location.py platform-location.py
COPY platform-location.cron /etc/cron.d/platform-location
RUN pip install -r requirements.txt
RUN chmod 0644 /etc/cron.d/platform-location
RUN touch /var/log/cron.log
RUN apt-get update && apt-get upgrade -y && apt-get -y install cron vim
CMD cron && tail -f /var/log/cron.log
could you help me, please?
PS: it is not duplicate of Python Logging in Docker because I want to see the output when I am running docker logs command not docker exec command. also I am using cron which the other question reporter does not use.
Solution
The issue is not with a python script, did you verify the cron logs without python for CMD cron && tail -f /var/log/cron.log
?
Use the below image, I am sure the above snippet will working fine but the cron not able to write logs to console so as a result the python will not write too.
Here is the working example.
FROM python:3.7-alpine3.9
COPY test.py /test.py
RUN cat /test.py
RUN echo "* * * * * echo hello" | crontab -
RUN echo "* * * * * python /test.py" | crontab -
CMD ["crond","-f"]
test.py
my_string = "Hello, World!"
print(my_string)
The image contain Python version 3.7.4
. You can change the base image to any python version will work fine if based on alpine.
Updated: Double-check your python file existence on the specified location, As here is the working example that you can try.
FROM python:3.6
RUN apt-get update && apt-get -y install cron vim
WORKDIR /opt/platform-location
RUN echo "* * * * * root /usr/local/bin/python /opt/platform-location/platform-location.py >> /var/log/cron.log 2>&1" >> /etc/cron.d/platform-location
RUN echo 'print ("hello World! ")' >> /opt/platform-location/platform-location.py
RUN chmod 0644 /etc/cron.d/platform-location
RUN touch /var/log/cron.log
CMD cron && tail -f /var/log/cron.log
Answered By - Adiii