在 docker 中分离运行时,Python 应用程序不打印任何内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29663459/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:51:36  来源:igfitidea点击:

Python app does not print anything when running detached in docker

pythondockerdockerfile

提问by jpdus

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

我有一个 Python (2.7) 应用程序,它在我的 dockerfile 中启动:

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

main.pyprints some strings when it is started and goes into a loop afterwards:

main.py在启动时打印一些字符串,然后进入循环:

print "App started"
while True:
    time.sleep(1)

As long as I start the container with the -it flag, everything works as expected:

只要我使用 -it 标志启动容器,一切都会按预期进行:

$ docker run --name=myapp -it myappimage
> App started

And I can see the same output via logs later:

稍后我可以通过日志看到相同的输出:

$ docker logs myapp
> App started

If I try to run the same container with the -d flag, the container seems to start normally, but I can't see any output:

如果我尝试使用 -d 标志运行同一个容器,该容器似乎正常启动,但我看不到任何输出:

$ docker run --name=myapp -d myappimage
> b82db1120fee5f92c80000f30f6bdc84e068bafa32738ab7adb47e641b19b4d1
$ docker logs myapp
$ (empty)

But the container still seems to run;

但容器似乎仍在运行;

$ docker ps
Container Status ...
myapp     up 4 minutes ... 

Attach does not display anything either:

附加也不显示任何内容:

$ docker attach --sig-proxy=false myapp
(working, no output)

Any ideas whats going wrong? Does "print" behave differently when ran in background?

任何想法出了什么问题?在后台运行时,“打印”的行为是否有所不同?

Docker version:

码头工人版本:

Client version: 1.5.0
Client API version: 1.17
Go version (client): go1.4.2
Git commit (client): a8a31ef
OS/Arch (client): linux/arm
Server version: 1.5.0
Server API version: 1.17
Go version (server): go1.4.2
Git commit (server): a8a31ef

采纳答案by jpdus

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 :

最后,我找到了一个在 Docker 中运行守护进程时查看 Python 输出的解决方案,这要感谢GitHub 上的@ahmetalpbalkan 。我自己在这里回答以供进一步参考:

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!

现在!

回答by Vitaly Isaev

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.

当我遇到同样的问题时,这对我有用。但是,说实话,我不知道为什么会发生这个错误。

回答by Victor

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

就我而言,运行 Python-u并没有改变任何东西。然而,诀窍是设置PYTHONUNBUFFERED=0为环境变量:

docker run --name=myapp -e PYTHONUNBUFFERED=0 -d myappimage

回答by Peter Senna

For me it is a feature, not a bug. Without a pseudo-TTY there is nothing to stdout to. So a simple solution is to allocate a pseudo-TTY for your running container with:

对我来说,这是一个功能,而不是一个错误。如果没有伪 TTY,就没有什么可标准输出的。因此,一个简单的解决方案是为您正在运行的容器分配一个伪 TTY:

$ docker run -t ...

回答by atline

See this articlewhich 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”.

通常有三种缓冲模式:

  • 如果文件描述符没有缓冲,则不会发生任何缓冲,读取或写入数据的函数调用会立即发生(并且会阻塞)。
  • 如果文件描述符是全缓冲的,则使用固定大小的缓冲区,并且 read 或 write 调用只是从缓冲区读取或写入。缓冲区在填满之前不会被刷新。
  • 如果文件描述符是行缓冲的,则缓冲会等待,直到看到换行符。所以数据会缓冲和缓冲直到看到\n,然后所有缓冲的数据在那个时间点被刷新。实际上,缓冲区通常有一个最大大小(就像在完全缓冲的情况下一样),因此该规则实际上更像是“缓冲直到看到换行符或遇到 4096 字节的数据,以先发生者为准”。

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

并且 GNU libc (glibc) 使用以下规则进行缓冲:

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 stdoutbecomes line-buffered, thus docker run --name=myapp -it myappimagecould see the one-line output.

所以,如果使用-t,从docker 文档,它会分配一个伪 tty,然后stdout变成line-buffered,从而docker run --name=myapp -it myappimage可以看到一行输出。

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

而且,如果只使用-d,不TTY被分配的话,stdoutfully-buffered,一条线App started肯定不能刷新缓冲区。

Then, use -dtto make stdout line bufferedor add -uin python to flush the bufferis the way to fix it.

然后,使用-dttomake stdout line buffered-u在 python 中添加toflush the buffer是修复它的方法。

回答by The Hog

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

如果更改print为 ,则可以在分离的图像上看到日志logging

main.py:

主要.py:

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

Dockerfile:

Dockerfile:

FROM python:2.7-stretch
ADD . /app
WORKDIR /app
CMD ["python","main.py"]

回答by Edward Aung

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.

使用 -t 添加 tty 也可以。您需要在 docker 日志中找到它。

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

使用大型日志输出,我没有将所有缓冲区存储在 dockers 日志中的任何问题。

回答by tycl

Since I haven't seen this answer yet:

因为我还没有看到这个答案:

You can also flush stdout after you print to it:

您还可以在打印后刷新 stdout:

import time

if __name__ == '__main__':
    while True:
        print('cleaner is up', flush=True)
        time.sleep(5)

回答by Adam Radestock

I had to use PYTHONUNBUFFERED=1in my docker-compose.yml file to see the output from django runserver.

我必须PYTHONUNBUFFERED=1在我的 docker-compose.yml 文件中使用才能查看 django runserver 的输出。

回答by Rich Hildebrand

If you want to add your print output to your Flask output when running docker-compose up, add the following to your docker compose file.

如果您想在运行时将打印输出添加到 Flask 输出中docker-compose up,请将以下内容添加到您的 docker compose 文件中。

web:
  environment:
    - PYTHONUNBUFFERED=1

https://docs.docker.com/compose/environment-variables/

https://docs.docker.com/compose/environment-variables/