Python app does not print anything when running detached in docker

前端 未结 11 1423
不思量自难忘°
不思量自难忘° 2020-11-29 16:54

I have a Python (2.7) app which is started in my dockerfile:

CMD [\"python\",\"main.py\"]

main.py prints some strings when it is s

相关标签:
11条回答
  • 2020-11-29 17:21

    You can see logs on detached image if you change print to logging.

    main.py:

    import time
    import logging
    print "App started"
    logging.warning("Log app started")
    while True:
        time.sleep(1)
    

    Dockerfile:

    FROM python:2.7-stretch
    ADD . /app
    WORKDIR /app
    CMD ["python","main.py"]
    
    0 讨论(0)
  • 2020-11-29 17:27

    Finally I found a solution to see Python output when running daemonized in Docker, thanks to @ahmetalpbalkan over at GitHub. Answering it here myself for further reference :

    Using unbuffered output with

    CMD ["python","-u","main.py"]
    

    instead of

    CMD ["python","main.py"]
    

    solves the problem; you can see the output (both, stderr and stdout) via

    docker logs myapp
    

    now!

    0 讨论(0)
  • 2020-11-29 17:29

    As a quick fix, try this:

    from __future__ import print_function
    # some code
    print("App started", file=sys.stderr)
    

    This works for me when I encounter the same problems. But, to be honest, I don't know why does this error happen.

    0 讨论(0)
  • 2020-11-29 17:31

    Usually, we redirect it to a specific file (by mounting a volume from host and writing it to that file).

    Adding a tty using -t is also fine. You need to pick it up in docker logs.

    Using large log outputs, I did not have any issue with buffer storing all without putting it in dockers log.

    0 讨论(0)
  • 2020-11-29 17:32

    In my case, running Python with -u didn't change anything. What did the trick, however, was to set PYTHONUNBUFFERED=0 as environment variable:

    docker run --name=myapp -e PYTHONUNBUFFERED=0 -d myappimage
    
    0 讨论(0)
提交回复
热议问题