如何在Jenkinsfile中停止正在运行的容器?
我有一个Jenkinsfile或Jenkins管道,该管道创建一个新图像并从该图像中启动一个容器。第一次运作良好。但是在随后的运行中,我希望停止并删除先前的容器。我的Jenkinsfile如下:
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。谢谢。
回答:
就像在此Jenkinsfile中一样,您可以改用sh命令。
这样,您可以使用以下行:
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)(如果正在运行)。
迈克尔A.指出在评论这不是一个妥善的解决办法,并承担码头工人正在安装的奴隶。
他指的是jenkinsci/plugins/docker/workflow/Docker.groovy,但Docker该类的容器方法尚未实现。
2018年8月更新:
Pieter Vogelaar在对“Jenkinsfile Docker管道多阶段 ” 的评论中指出,他写道:
通过使用全局
pipelineContext对象,可以进一步使用返回的容器对象。
它是:
pipelineContext全局变量,其类型为LinkedHashMap。Jenkinsfile编程语言是Groovy。在Groovy中,这几乎等同于JavaScript对象。该变量可以在阶段之间共享数据或对象。
因此,这是一个声明性管道,以:
// Initialize a LinkedHashMap / object to share between stagesdef pipelineContext = [:]
以上是 如何在Jenkinsfile中停止正在运行的容器? 的全部内容, 来源链接: utcz.com/qa/429541.html







