How do I stop a running container in Jenkinsfile?

…衆ロ難τιáo~ 提交于 2019-12-03 04:51:29

As in this Jenkinsfile, you can use sh commands instead.

That way, you can use lines like:

sh 'docker ps -f name=zookeeper -q | xargs --no-run-if-empty docker container stop'
sh 'docker container ls -a -fname=zookeeper -q | xargs -r docker container rm'

That would ensure a container x (here named zookeper), if it was running, is first stopped and removed.

Michael A. points out in the comments this is not a proper solution, and assume docker being installed on the slave.
He refers to jenkinsci/plugins/docker/workflow/Docker.groovy, but a container method for the Docker class is not implemented yet.


Update August 2018:

Pieter Vogelaar points out in the comments to "Jenkinsfile Docker pipeline multi stage" he wrote about:

By using a global pipelineContext object, it's possible to use the returned container object in a further stage.

It is:

pipelineContext global variable which is of type LinkedHashMap.
The Jenkinsfile programming language is Groovy. In the Groovy this comes close to the equivalent of the JavaScript object. This variable makes it possible to share data or objects between stages.

So this is a Declarative Pipeline, starting with:

// Initialize a LinkedHashMap / object to share between stages
def pipelineContext = [:]

By using a global pipelineContext object, it's possible to use the returned container object in a further stage. Or for example in the post build step that must always be executed, also for a failed build. This way Docker containers are always stopped and removed at the very end of a build. I described a working solution at http://pietervogelaar.nl/jenkinsfile-docker-pipeline-multi-stage.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!