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 {
                     "ARTIFACTORY_USER=${IC_ARTIFACTORY_USER}"]) {
                        string(credentialsId: IC_ARTIFACTORY_KEY, variable: 'ARTIFACTORY_KEY')
                ]) {
                    sh '''
                    bash -x
        } finally { }

If 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?

2 answers

  • answered 2018-11-08 09:01 chenchuk

    You can ensure the command will not fail using this :

    bash -x || true

    Or even better :

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

  • answered 2018-11-08 09:02 fab

    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

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

    (from docs)