执行代码后停止Docker容器

jz2*_*z22 5 python docker dockerfile docker-image

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

Dockerfile:

FROM python:3

ADD aa.py /

CMD [ "python", "./aa.py" ]
Run Code Online (Sandbox Code Playgroud)

蟒蛇:

print('Hello!')
Run Code Online (Sandbox Code Playgroud)

错误信息:

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
Run Code Online (Sandbox Code Playgroud)

Von*_*onC 3

注意:默认CMDpython:3.python3

退出代码 143 的含义SIGTERM如此处所述。这就是docker 发送的内容
所以你需要你的python3 应用程序优雅地处理 SIGTERM 信号

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

OP在评论中添加:

与此同时,我发现SIGTERM在 Docker 环境中处理起来效果非常好。

然而,在 CloudFoundry 上的 Docker 中使用相同的代码并不能防止容器崩溃。
在 CloudFoundry 中,您需要一个始终运行的应用程序,而不是像脚本一样只执行任务然后停止。
即使没有错误地停止,也会在 CloudFoundry 中被检测为崩溃。

我使用 Flask 框架将脚本转换为 REST 服务器。现在它始终在运行,但仅在通过其 url 调用时执行其任务。