如何在Jenkinsfile中停止正在运行的容器?

我有一个Jenkinsfile或一个Jenkinspipe道创build一个新的图像,并启动一个容器的图像。 它第一次运作良好。 但在后续运行中,我想要停止并移除先前的容器。 我的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停止容器”阶段失败。 这是因为我不知道正确的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 ),如果它正在运行,首先停止并删除。