How to retain docker container after Jenkins pipeline build completed

Viewed 272

We've a Jenkins pipeline which runs on docker container and deploy app in tomcat but as soon as pipeline build completes, docker container is destroyed, hence we cannot access the installed app-

Is there a way to retain docker container started through Jenkins pipeline after build finishes.

Pipeline sample code:

pipeline {
    agent {
        docker {
            label '<label-name>'
            image '<image-name>'
            args '--cap-add SYS_ADMIN --cap-add DAC_READ_SEARCH -v $HOME/mavenrepo/module/repository:/usr/share/.m2/repository --user root --memory=9g'
        }
    }
    stages {
        //Few required stages here

        stage('Start Application server'){
            steps{
                script{
                    FAILED_STAGE = env.STAGE_NAME

                    //startApplicationServer()
                    //checkServerStarted()
                }
            }
        }
    }
}

At the end of pipeline build, container destroy code is seen -

$ docker stop --time=1 b8445c83d7c9d08231c27f4f03f486d021fa1c0fa1d89c189231b069a2fbbf
$ docker rm -f b8445c83d7c9d08231c27f4f03f486d021fa1c0fa1d89c189231b069a2fbbf
[Pipeline] // withDockerContainer
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
1 Answers

My solution: In the pipeline, share the socket with the newly created container

pipeline {
    agent {
        docker {
            image 'ubuntu'
            args '-v /var/run/docker.sock:/var/run/docker.sock'
        }
    }

Then, in the job, create a new image out of the one you are running:

docker commit $(basename $(cat /proc/1/cpuset)) foo 

$(basename $(cat /proc/1/cpuset)) gets the hash of the current container as found [here][1]

foo being the name of the new image

Related