问题
I'm using the Docker Pipeline Plugin to execute my build scripts via Docker containers. I noticed that if I had a script return a non-zero exit code when executing within an inside()
command, Jenkins would mark the pipeline execution as a failure. This example Jenkinsfile illustrates that scenario:
docker.image('alpine').inside() {
sh 'exit 1'
}
However, if I use the withRun()
command, a similar Jenkinsfile will not cause the build to fail, even though the docker ps -l
command shows that the container exited with a non-zero status:
node() {
sh 'touch ./test.sh'
sh 'echo "exit 1" >> ./test.sh'
sh 'chmod 755 ./test.sh'
docker.image('alpine').withRun("-v ${WORKSPACE}:/newDir", '/bin/sh /newDir/test.sh') {container ->
sh "docker logs ${container.id} -f"
sh 'docker ps -l'
}
}
Is there a way to make withRun()
fail the build if the container exits with a non-zero code?
回答1:
I couldn't find any more information on exit codes from the withRun()
command, so I ended up just executing a docker run
command from an sh
step:
node() {
sh 'touch ./test.sh'
sh 'echo "exit 1" >> ./test.sh'
sh 'chmod 755 ./test.sh'
sh "docker run --rm -v ${WORKSPACE}:/newDir alpine /bin/sh /newDir/test.sh"
}
回答2:
One of possible solutions:
docker.withRegistry("https://${REGISTRY}", 'creds-id') {
stage("RUN CONTAINER"){
Image = docker.image("${IMAGE}-${PROJECT}:${TAG}")
try {
c = Image.run("-v /mnt:/mnt")
sh "docker logs -f ${c.id}"
def out = sh script: "docker inspect ${c.id} --format='{{.State.ExitCode}}'", returnStdout: true
sh "exit ${out}"
} finally {
c.stop()
}
}
}
回答3:
How about docker wait?
sh "exit $(docker wait ${container.id})"
wait
prints the container's exit code, which in case of error causes the build to fail according to sh docs:
Normally, a script which exits with a nonzero status code will cause the step to fail with an exception.
来源:https://stackoverflow.com/questions/44687787/how-do-i-fail-a-jenkins-build-if-a-docker-pipeline-plugin-withrun-command-return