gpt4 book ai didi

python - 执行代码后停止 Docker 容器

转载 作者:行者123 更新时间:2023-12-04 20:31:45 26 4
gpt4 key购买 nike

为了更深入地了解 Docker,我创建了一个执行 python 脚本的 dockerfile。它工作正常,但在执行脚本后容器崩溃。如何修改我的 dockerfile 以便在执行后销毁容器,而不是让容器一直崩溃并重新启动?

Dockerfile:

FROM python:3

ADD aa.py /

CMD [ "python", "./aa.py" ]

Python:
print('Hello!')

错误信息:
2017-06-14 11:37:09 [CELL/0] OUT Starting health monitoring of container
2017-06-14 11:37:09 [APP/PROC/WEB/0] OUT Hello!
2017-06-14 11:37:09 [APP/PROC/WEB/0] OUT Exit status 0
2017-06-14 11:37:09 [CELL/0] OUT Exit status 143
2017-06-14 11:37:09 [CELL/0] OUT Destroying container
2017-06-14 11:37:09 [API/0] OUT Process has crashed with type: "web"
2017-06-14 11:37:09 [API/0] OUT App instance exited with guid 6fdede46-6751-4725-ad78-b76262dbe701 payload: {"instance"=>"", "index"=>0, "reason"=>"CRASHED", "exit_description"=>"2 error(s) occurred:\n\n* 2 error(s) occurred:\n\n* Codependent step exited\n* cancelled\n* cancelled", "crash_count"=>4, "crash_timestamp"=>1497433029411246770, "version"=>"98e2a035-e38f-4169-95fb-2701c8486e9c"}
2017-06-14 11:37:09 [CELL/0] OUT Successfully destroyed container
2017-06-14 11:38:31 [CELL/0] OUT Creating container

最佳答案

注意:默认 CMD for python:3 is python3 .

exit code 143 means SIGTERM mentioned here .即 what docker sends .
所以您需要为您的 python3 application to process SIGTERM signal gracefully

不要忘记,您的python 应用程序一旦完成并退出main 函数,就会导致容器自动停止并退出。

The OP添加 in the comments :

In the meantime, I have found out that handling the SIGTERM in the Docker environment works perfectly fine.

However using the same code in Docker on CloudFoundry does not prevent the container from crashing.
In CloudFoundry you need an application that is always running and not just doing a task and then stopping like a script does.
Even stopping without errors is detected as a crash in CloudFoundry.

I transformed my script into a REST server by using the flask framework. Now it is always running but only doing its task when being called via its url.

关于python - 执行代码后停止 Docker 容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44541063/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com