Python app does not print anything when running detached in docker

前端 未结 11 1500
不思量自难忘°
不思量自难忘° 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:11

    See this article which explain detail reason for the behavior:

    There are typically three modes for buffering:

    • If a file descriptor is unbuffered then no buffering occurs whatsoever, and function calls that read or write data occur immediately (and will block).
    • If a file descriptor is fully-buffered then a fixed-size buffer is used, and read or write calls simply read or write from the buffer. The buffer isn’t flushed until it fills up.
    • If a file descriptor is line-buffered then the buffering waits until it sees a newline character. So data will buffer and buffer until a \n is seen, and then all of the data that buffered is flushed at that point in time. In reality there’s typically a maximum size on the buffer (just as in the fully-buffered case), so the rule is actually more like “buffer until a newline character is seen or 4096 bytes of data are encountered, whichever occurs first”.

    And GNU libc (glibc) uses the following rules for buffering:

    Stream               Type          Behavior
    stdin                input         line-buffered
    stdout (TTY)         output        line-buffered
    stdout (not a TTY)   output        fully-buffered
    stderr               output        unbuffered
    

    So, if use -t, from docker document, it will allocate a pseudo-tty, then stdout becomes line-buffered, thus docker run --name=myapp -it myappimage could see the one-line output.

    And, if just use -d, no tty was allocated, then, stdout is fully-buffered, one line App started surely not able to flush the buffer.

    Then, use -dt to make stdout line buffered or add -u in python to flush the buffer is the way to fix it.

提交回复
热议问题