Evan Gertis
Evan Gertis

Reputation: 2062

How to build maven in Docker build file

I have been desperately trying to figure out if it's possible to build a mvn project on a jenkins agent with a docker build file. The error that I am getting from running the pipeline is [ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile

pipeline {
    agent {
        dockerfile { 
            filename 'DockerFile.build'
        }
    }
    environment {
        JAVA_HOME="/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.272.b10-1.el8_2.x86_64"
    }
    stages {
        stage('Build DockerFile') {
            steps {
                echo "building docker image"
                sh "echo 1 | alternatives --config java"
                sh "java -version"
                sh "echo ${JAVA_HOME}"

                git branch: "develop", credentialsId: 'cred_id', url: "[email protected]:repo.git"
                dir("repo"){
                    sh "mvn clean install -X"
                }
            }
        }
    }
}

DockerFile.build

FROM centos

RUN yum update -y
RUN yum install -y java-11-openjdk-devel
RUN yum install -y java-11-openjdk

RUN yum install -y maven


ENV HOME=${home}

The line about echo 1 | alternatives --config java is to switch to java 11. Any help would be greatly appreciated.

Upvotes: 0

Views: 1596

Answers (2)

Rob Evans
Rob Evans

Reputation: 2874

Seems like you have a docker build file (Dockerfile) that you want to build so you have a reusable image. Once you have the image you can push it to a registry (like Dockerhub) or run it with your application code mounted inside. If you first want to push the image to a registry, you can then pull it down and run it... much the same way as you'd pull any other docker image down and run it.

I answered a similar question recently here: Dockerfile can't build app with Maven - No goals specified for this build Perhaps this helps?

Seems like you have an error because you're attempting to build directly on the jenkins host rather than in the docker container with maven/java11 installed.

Its a common mistake to think you're within a docker container on a host, when in fact you're just on the host and the container is running within it without your realising. Check docker ps -a if this is the case to get the container ID and then you open a terminal within it using docker exec -it bash or docker exec -it sh

Upvotes: 2

Evan Gertis
Evan Gertis

Reputation: 2062

docker {
            image 'maven:3-alpine'
            args '-v $HOME/.m2:/root/.m2'
        }

Need to mount the .m2 dir. It's under Caching containers here: https://www.jenkins.io/doc/book/pipeline/docker/

Upvotes: 0

Related Questions