如何在Jenkinsfile中停止正在运行的容器? [英] How do I stop a running container in Jenkinsfile?

查看:499
本文介绍了如何在Jenkinsfile中停止正在运行的容器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Jenkinsfile或Jenkins管道,该管道创建一个新图像并从该图像中启动一个容器.第一次运作良好.但是在随后的运行中,我希望停止并删除先前的容器.我的Jenkinsfile如下:

I have a Jenkinsfile or a Jenkins pipeline which creates a new image and starts a container out of that image. It works well for the first time. But on subsequent runs, I want the previous container to be stopped and removed. My Jenkinsfile is as follows:

node {
   def commit_id
   stage('Preparation') {
     checkout scm
     sh "git rev-parse --short HEAD > .git/commit-id"                        
     commit_id = readFile('.git/commit-id').trim()
   }
   stage('docker build/push') {
     docker.withRegistry('https://index.docker.io/v1/', 'dockerhub') {
       def app = docker.build("my-docker-id/my-api:${commit_id}", '.').push()
     }
   }
   stage('docker stop container') {
       def apiContainer = docker.container('api-server')
       apiContainer.stop()
   }
   stage('docker run container') {
       def apiContainer = docker.image("my-docker-id/my-api:${commit_id}").run("--name api-server --link mysql_server:mysql --publish 3100:3100")
   }
}

"docker stop container"阶段失败.那是因为我不知道获取容器并停止它的正确API.谢谢.

The stage 'docker stop container' is failing. That is because I don't know the right API to get the container and stop it. Thanks.

推荐答案

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'

这将确保容器x(在此名为zookeper)正在运行时,首先将其停止并删除.

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

Michael A. 指出

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.

2018年8月更新:

Update August 2018:

Pieter Vogelaar 在对"

通过使用全局pipelineContext对象,可以在以后的阶段中使用返回的容器对象.

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

是:

pipelineContext全局变量,其类型为LinkedHashMap.
Jenkinsfile编程语言是Groovy.在Groovy中,这几乎等同于JavaScript对象.通过此变量,可以在阶段之间共享数据或对象.

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 = [:]

这篇关于如何在Jenkinsfile中停止正在运行的容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆