What is the proper way to stop and remove a docker container in Jenkins when using Docker Pipeline Plugin? -
i have jenkins pipeline builds , runs docker machine, not agent, using scripting block along docker pipeline plugin methods docker.build()
, image.run()
. works fine if build fails, docker container left running! have container.stop()
in post{ always{} }
block doesn't seem work. don't want ssh jenkins server delete container after every build , can't leave because has specific , necessary name. how stop , rm container regardless of failure of build?
my pipeline:
pipeline { agent none stages { stage('checkout') { agent steps { checkout([$class: 'gitscm', branches: [[name: '*/master']], dogeneratesubmoduleconfigurations: false, extensions: [], submodulecfg: [], userremoteconfigs: [[credentialsid: '<some credentials>', url: '<a git repo>']]]) } } stage('spin receiver') { agent steps { script { def receiver = docker.build("receiver", "--rm centos7_receiver") def receiver_container = receiver.run("-d -v ${pwd}/realtime_files/station_name/201707/f/20170710_191:/dsk1/ssn/log0_f/17001 --network='rsync_test' --name='test_receiver'") } } } stage('run tests') { agent { dockerfile { args '-v /etc/passwd:/etc/passwd --network="rsync_test"' } } steps { sh "python ./rsyncunittests.py" } } } post { { script { receiver_container.stop() } } failure { sendemail('foo@bar.com') } changed { sendemail('foo@bar.com') } } }
here working solution. have define variable container outside main pipeline. can use anywhere in pipeline start or stop container. in particular, can remove container in post{ always{ } }
.
def receiver_container pipeline { agent stages { stage('checkout') { agent steps { checkout([$class: 'gitscm', branches: [[name: '*/master']], dogeneratesubmoduleconfigurations: false, extensions: [], submodulecfg: [], userremoteconfigs: [[credentialsid: '<some credentials>', url: '<a git repo>']]]) } } stage('spin receiver') { agent steps { script { def receiver = docker.build("receiver", "--rm receiver_docker") receiver_container = receiver.run("-d -u 0:0 -v /var/lib/jenkins/workspace/rsyncrealtime/jenkins_rt:/dsk1/ssn/log5_f/17191 --network='rsync_test' --name='test_receiver'") } } } stage('run unit tests') { agent { dockerfile { args '-u 0:0 -v /etc/passwd:/etc/passwd --network="rsync_test"' } } steps { sh "sshpass -p 'test' ssh anonymous@test_receiver ls -l /dsk1/ssn/log5_f/17191" sh "python ./rsyncunittests.py" } } } post { { script { receiver_container.stop() } } failure { sendemail('foo@bar.com') } changed { sendemail('foo@bar.com') } } }
Comments
Post a Comment