我有一个Python(2.7)应用程序,它在我的dockerfile中启动:
CMD ["python","main.py"]
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 ...
Attach也不显示任何东西:
$ docker attach --sig-proxy=false myapp
(working, no output)
有什么问题吗?“打印”在后台运行时表现不同吗?
码头工人版本:
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
最后,我找到了一个在Docker中运行daemonized时查看Python输出的解决方案,这要感谢GitHub上的@ ahmetalbalkan。我自己在这里回答,以供进一步参考:
使用无缓冲输出
CMD ["python","-u","main.py"]
而不是
CMD ["python","main.py"]
解决问题;您现在可以通过via看到输出(包括stderr和stdout)
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;
最后,我找到了一个在Docker中运行daemonized时查看Python输出的解决方案,这要感谢GitHub上的@ ahmetalbalkan。我自己在这里回答,以供进一步参考:
使用无缓冲输出
CMD ["python","-u","main.py"]
而不是
CMD ["python","main.py"]
解决问题;您现在可以通过via看到输出(包括stderr和stdout)
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;