Python app does not print anything when running de

2019-01-16 17:44发布

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

4条回答
▲ chillily
2楼-- · 2019-01-16 17:59

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
查看更多
放荡不羁爱自由
3楼-- · 2019-01-16 18:03

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:

$ docker run -t ...
查看更多
欢心
4楼-- · 2019-01-16 18:03

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.

查看更多
看我几分像从前
5楼-- · 2019-01-16 18:14

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!

查看更多
登录 后发表回答