简体   繁体   中英

How to use Jenkins Docker plugin to build a maven project inside a container

Working on a project which uses maven as the build tool. Now when using Jenkins for deployment, we need to build the project inside a docker container using Docker plugin. My understanding is that the project should be build inside the container and once done it should be deleted.

I am trying to use command similar to : docker.image("imageName").inside{} Now how do we make sure that the container is deleted and mount a volume so that the jar created as part of build can be accessed after docker container deletion ?

Can some provide inputs on the above understanding and an example of the above command or any link to refer to ?

I think, it will be good if you will use pipeline job. Here you can check my example with comments

pipeline {
stages {
    stage('Build') {
        agent { //here we select only docker build agents
            docker {
                image 'maven:latest' //container will start from this image
                args '-v /root/.m2:/root/.m2' //here you can map local maven repo, this let you to reuse local artifacts
            }
        }
        steps {
            sh 'mvn -B -DskipTests clean package' //this command will be executed inside maven container
        }
    }
    stage('Test') { //on this stage New container will be created, but current pipeline workspace will be remounted to it automatically
        agent {
            docker {
                image 'maven:latest'
                args '-v /root/.m2:/root/.m2'
            }
        }
        steps {
            sh 'mvn test' 
        }
    }
    stage ('Build docker image') { //here you can check how you can build even docker images inside container
        agent {
            docker {
                image 'maven:latest'
                args '-v /root/.m2:/root/.m2 -v /var/run/docker.sock:/var/run/docker.sock' //here we expose docker socket to container. Now we can build docker images in the same way as on host machine where docker daemon is installed
            }
        }
        steps {
            sh 'mvn -Ddocker.skip=false -Ddocker.host=unix:///var/run/docker.sock docker:build' //example of how to build docker image with pom.xml and fabric8 plugin
        }
    }
}

}

This will work even if Jenkins itself run in a container with mounter jenkins_home from host.

Please let me know if i can provide more helpfull details from my experience to you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM