ybonda
ybonda

Reputation: 1710

How to prevent from docker to stop/remove the container on error

Consider I have a Jenkins groovy code that runs docker container and some bash will run inside of it:

    docker.withRegistry(dockerRegistry, dockerCredentials) {
    docker.image(new String(dockerImage + ":" + dockerVersion)).inside(mountCommand) {

        try {
            withEnv(["AWS_PROFILE=${mappings['stackEnv']}",
                     "FULL_PACKAGE_VERSION=${mappings['revision']}",
                     "ARTIFACTORY_USER=${IC_ARTIFACTORY_USER}"]) {
                withCredentials([
                        string(credentialsId: IC_ARTIFACTORY_KEY, variable: 'ARTIFACTORY_KEY')
                ]) {
                    sh '''
                    bash -x Jenkinsfile-e2e-test.sh
                '''
                }
            }
        } finally { }
    }
}

If Jenkinsfile-e2e-test.sh falls for some reason then Jenkins will automatically stop and remove the container:

09:40:08 $ docker stop --time=1 6e78cf6d940cb1ca1cb1c729617fd3e6ba3fa4085c2750908dff8f2a1e7ffeed
09:40:09 $ docker rm -f 6e78cf6d940cb1ca1cb1c729617fd3e6ba3fa4085c2750908dff8f2a1e7ffeed

How do I prevent Jenkins to destroy the container on failure?

Upvotes: 1

Views: 1866

Answers (2)

Fabian Braun
Fabian Braun

Reputation: 3930

Jenkins will always stop and remove the container, once the body of your .inside command is finished. No matter if your bash script succeeds or fails.

The rational behind is that jenkins takes care of the housekeeping for you, to prevent that you end up with lots of stopped containers hanging around on your build machine.

This is the case for the Image.withRun and Image.inside methods. If you want to have control over the lifecycle of the container you should use Image.run:

Uses docker run to run the image, and returns a Container which you could stop later

(from docs)

Upvotes: 2

chenchuk
chenchuk

Reputation: 5742

You can ensure the command will not fail using this :

bash -x Jenkinsfile-e2e-test.sh || true

Or even better :

bash -x Jenkinsfile-e2e-test.sh > e2e.log 2>&1 & || true
# check the log file and do something based on the log

Upvotes: 1

Related Questions