为什么在独立的Docker容器中运行时,为什么不打印任何东西?

发布于 2025-02-03 10:51:21 字数 1180 浏览 5 评论 0 原文

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

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

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

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

只要我用-IT启动容器,标志,一切都按预期工作:

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

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

$ docker logs myapp
> App started

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

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

但是容器似乎仍在运行;

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

附件也没有显示任何内容:

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

有什么想法出了什么问题?在背景中运行时,“打印”行为会有所不同吗?

Docker版本:

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

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 started and goes into a loop afterwards:

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

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

$ 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:

$ 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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(16

半枫 2025-02-10 10:51:21

最后,我找到了一个解决方案,可以在docker中奔跑时看到python输出,这要归功于@AhmetalPbalkan在 github 。我自己在这里回答它以供进一步参考:

使用未掩盖的输出

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

而不是

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

解决问题;您可以通过

docker logs myapp

为什么 -U ref

- print is indeed buffered and docker logs will eventually give you that output, just after enough of it will have piled up
- executing the same script with python -u gives instant output as said above
- import logging + logging.warning("text") gives the expected result even without -u

python -u ref的含义。 > python -Help | grep- -u

-u     : force the stdout and stderr streams to be unbuffered;

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 now (both, stderr and stdout) via

docker logs myapp

why -u ref

- print is indeed buffered and docker logs will eventually give you that output, just after enough of it will have piled up
- executing the same script with python -u gives instant output as said above
- import logging + logging.warning("text") gives the expected result even without -u

what it means by python -u ref. > python --help | grep -- -u

-u     : force the stdout and stderr streams to be unbuffered;
场罚期间 2025-02-10 10:51:21

就我而言,使用 -U 运行Python没有更改任何内容。然而,哪些技巧是将 pythonunbuffered设置为环境变量:

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

[edit]:更新 pythonunbuffered = 0 to pythonunbuffered = 1 在拉尔斯发表评论之后。这不会改变行为并增加清晰度。

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

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

[Edit]: Updated PYTHONUNBUFFERED=0 to PYTHONUNBUFFERED=1 after Lars's comment. This doesn't change the behavior and adds clarity.

木槿暧夏七纪年 2025-02-10 10:51:21

如果您想在运行 Docker-Compose 时将打印输出添加到烧瓶输出中,请在Docker组成的文件中添加以下内容。

web:
  environment:
    - PYTHONUNBUFFERED=1

https://docs.docker.com/compose/compose/environment-vironment-variariables/

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.

web:
  environment:
    - PYTHONUNBUFFERED=1

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

故事灯 2025-02-10 10:51:21

参见本文解释了行为的详细原因:

通常有三种用于缓冲的模式:

  • 如果文件描述符未掩盖,则不会发生任何缓冲,并且会立即发生读取或写入数据的函数调用(并将阻止)。
  • 如果文件描述符完全缓冲,则使用固定尺寸的缓冲区,并且只需从缓冲区读取或写入呼叫即可。缓冲区直到填充后才冲洗。
  • 如果文件描述符被线缓冲,则缓冲等待,直到看到一个newline字符。因此,数据将缓冲和缓冲区直至看到A \ n,然后在此时间点被缓冲的所有数据冲洗。实际上,缓冲区通常有最大尺寸(就像在完全缓冲的情况下一样),因此该规则实际上更像是“直到看到newline字符或遇到4096字节的数据,遇到了首先发生的数据”。<<<<<<<<<<<<<<<<<<< /li>

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

因此,如果使用 -t ,则来自 docker文档,它将分配一个伪tty,然后 stdout 变成 line-buffered ,因此 docker run -name = myApp- it myAppimage 可以看到单行输出。

而且,如果只使用 -d ,则没有分配TTY,那么, stdout is 完全buffered ,一行应用程序启动启动< /代码>肯定无法冲洗缓冲区。

然后,将 -dt 用于使Stdout行缓冲或在Python中添加 -U flush flush flush the Buffer 是修复它的方法。

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.

情域 2025-02-10 10:51:21

由于我还没有看到这个答案:

印刷后,您也可以冲洗出来:

import time

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

Since I haven't seen this answer yet:

You can also flush stdout after you print to it:

import time

if __name__ == '__main__':
    while True:
        print('cleaner is up', flush=True)
        time.sleep(5)
莳間冲淡了誓言ζ 2025-02-10 10:51:21

尝试将这两个环境变量添加到您的解决方案 pythonunbuffered = 1 pythonioEncoding = utf-8

Try to add these two environment variables to your solution PYTHONUNBUFFERED=1 and PYTHONIOENCODING=UTF-8

绝情姑娘 2025-02-10 10:51:21

如果您将打印更改为记录,则可以在分离的图像上看到日志。

main.py:dockerfile

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

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

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"]
红ご颜醉 2025-02-10 10:51:21

如果有人使用Conda运行Python应用程序,则应将 - Nocapture-Output 添加到命令中,因为Conda缓冲区默认为STDOUT。

ENTRYPOINT ["conda", "run", "--no-capture-output", "-n", "my-app", "python", "main.py"]

If anybody is running the python application with conda you should add --no-capture-output to the command since conda buffers to stdout by default.

ENTRYPOINT ["conda", "run", "--no-capture-output", "-n", "my-app", "python", "main.py"]
陪你到最终 2025-02-10 10:51:21

我必须在我的docker-compose.yml文件中使用 pythonunbuffered = 1 来查看Django Runserver的输出。

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

天赋异禀 2025-02-10 10:51:21

作为快速修复,请尝试以下操作:

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

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

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.

镜花水月 2025-02-10 10:51:21

如果您不使用 Docker-Compose ,而只是正常 docker ,则可以将其添加到 dockerfile ,该正在托管flask应用程序

ARG FLASK_ENV="production"
ENV FLASK_ENV="${FLASK_ENV}" \
    PYTHONUNBUFFERED="true"

CMD [ "flask", "run" ]

If you aren't using docker-compose and just normal docker instead, you can add this to your Dockerfile that is hosting a flask app

ARG FLASK_ENV="production"
ENV FLASK_ENV="${FLASK_ENV}" \
    PYTHONUNBUFFERED="true"

CMD [ "flask", "run" ]
杀お生予夺 2025-02-10 10:51:21

使用 python manage.py runserver django应用程序时,添加环境变量 pythonunbuffered = 1 解决了我的问题。 print('helloworld',flush = true)也对我有用。

但是, Python -U 对我不起作用。

When using python manage.py runserver for a Django application, adding environment variable PYTHONUNBUFFERED=1 solve my problem. print('helloworld', flush=True) also works for me.

However, python -u doesn't work for me.

别想她 2025-02-10 10:51:21

我将Visual Studio代码与Docker扩展名一起自动创建Python。

默认情况下,它具有此行,

# Turns off buffering for easier container logging
ENV PYTHONUNBUFFERED=1

它可以正常工作并显示集装箱以独立模式运行时的日志,因此我认为这是首选的方式。我使用python 3.11

I use visual studio code with docker extension to create Dockerfile in python automatically.

By default it have this line

# Turns off buffering for easier container logging
ENV PYTHONUNBUFFERED=1

it works and show logs when container run in detached mode, so I think that's the preferred way. I use python 3.11

逆光下的微笑 2025-02-10 10:51:21

通常,我们将其重定向到特定文件(通过将卷从主机安装并将其写入该文件)。

使用-t添加TTY也可以。您需要在Docker日志中拾取它。

使用大型日志输出,我没有任何问题,而无需将其放入Dockers日志中。

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.

有深☉意 2025-02-10 10:51:21

对于最终在这里的任何人,我都尝试了其中一系列解决方案,但没有人对我有用。最后,我需要通过

logging.basicConfig(level=logging.INFO)

在实例化logger实例之前

logger = logging.getLogger()

添加添加来配置我的记录器,这效果很好,而我不必进行其他任何更改。

For anyone who ends up here, I tried a bunch of these solutions but none worked for me. In the end I needed to propertly configure my logger by adding

logging.basicConfig(level=logging.INFO)

before I instantiated my logger instance

logger = logging.getLogger()

This worked perfectly and I didn't have to make any other changes.

深巷少女 2025-02-10 10:51:21

对我来说,这里的答案都没有。

为了查看消息,我的python程序正在打印到docker容器中的stdout,我必须添加:

tty:true

我的docker服务中的python服务 compose.yaml

https://docs.docker.com/compose/compose/compose/compose-fose-file/05 - 服务/#tty

For me none of the answers here worked.

In order to see messages my Python program was printing to stdout within a Docker container I had to add:

tty: True

for my Python service in my docker compose.yaml

https://docs.docker.com/compose/compose-file/05-services/#tty

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文