执行代码后停止Docker容器

时间:2017-06-14 09:42:53

标签: python docker dockerfile docker-image

为了更深入地了解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

1 个答案:

答案 0 :(得分:2)

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

exit code 143 means SIGTERMmentioned here。那是what docker sends 所以你需要python3 application to process SIGTERM signal gracefully

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

The OP添加in the comments

  

与此同时,我发现处理Docker环境中的SIGTERM非常合适。

     

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

     

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

相关问题