问题描述
# entry.py
import time
while True:
print("hello")
time.sleep(2)
FROM python:3.9
copY entry.py entry.py
CMD python entry.py
首先我构建docker镜像:
$ docker build -t dtest .
现在我使用 -it
选项运行它,它按预期工作。
$ docker run -it dtest
# hello printed to screen every two seconds
但是当我在分离模式下运行它,然后尝试查看日志时,我什么也没看到。
$ docker run -d dtest
e19f7285c098af582e163354be84774d1307b2409337cb03bdd217292899bdb7
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
e19f7285c098 dtest "/bin/sh -c 'python …" 20 seconds ago Up 18 seconds epic_chatterjee
$ docker logs epic_chatterjee
# nothing is shown,exits
$ docker logs -f epic_chatterjee
# a cursor keeps blinking but nothing shown
解决方法
这与 Python 缓冲输出的方式有关。由于写入 stdout 的计算成本很高,因此它会尝试收集大缓冲区,并且仅在没有连接终端的情况下偶尔刷新它们。
您可以将 Python 代码更改为:
print("Hello",flush=True)
或者运行带有 python
标志的 -u
以强制无缓冲输出
FROM python:3.9
COPY entry.py entry.py
ENTRYPOINT ["python","-u"]
CMD ["entry.py"]