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")
}
}
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.
sh 'docker container rm -f api-server'
– Traction