Jenkins uses Maven to build Java applications

This tutorial will show you how to use Jenkins to orchestrate and build a simple Java application managed with Maven.

If you are a Java developer using Maven and are new to CI/CD concepts, or maybe you are familiar with the concepts but don’t know how to implement building applications with Jenkins, then this tutorial is for you.

You’ll get a simple Java application that outputs the “Hello world!” string in the Github examples repository, and includes several unit tests that check the main method. Test results are saved in JUnit XML reports.

Time-consuming: If your machine meets the configuration requirements, it will take 20-40 minutes to complete this tutorial. The exact time depends on the performance of your machine, and whether you have completed the tutorial on running Jenkins in Docker, please refer to another tutorial.

You can stop this tutorial at any point and continue from where you left off.

If you have already completed another tutorial, you can skip the configuration requirements and running Jenkins in Docker chapters, and continue to fork the example repository (make sure you have Git installed locally). If you need to restart Jenkins, see Stopping and Restarting Jenkins.

configuration requirements
For this tutorial, you will need:

  • A machine with macOS, Linux or Windows operating system installed, with the following configurations:

    • The minimum memory is 256MB, and 512MB or more is recommended.

    • 10GB of hard disk space for installing Jenkins, your Docker images and containers.

  • The following software is installed:

    • Docker – Read more in the Installing Docker section of the Installing Jenkins page.
      Note: If you are using Linux, this tutorial assumes that you are not running Docker commands as root, but are using a single user account to access the other tools used in this tutorial.

    • Git and GitHub Desktop

Run Jenkins in Docker

In this tutorial, Jenkins is run as a Docker container from the jenkinsci/blueocean Docker image.

To run Jenkins in Docker, follow the instructions in the relevant documentation below for macOS and Linux or Windows. .

You can read more about Docker container and image concepts in the Downloading and running Jenkins in Docker section of the Docker and Installing Jenkins page.

On macOS and Linux systems

  1. Open a terminal window

  2. Use the following docker run command to run the jenkinsci/blueocean image as a container in Docker (remember, this command will download it automatically if there is no image locally):

    docker run \
      --rm \
      -u root \
      -p 8080:8080\
      -v jenkins-data:/var/jenkins_home \
      -v /var/run/docker.sock:/var/run/docker.sock \
      -v "$HOME":/home\
      jenkinsci/blueocean
    Map the /var/jenkins_home directory in the container to the Docker volume and name it jenkins- data. If the volume does not exist, the docker run command will automatically create the volume for you.
    Map the `$HOME` directory on the host (ie your local) to (usually /Users/ directory) to the container’s /home directory.

    Note: If copying or pasting the command snippet above doesn’t work, try copying and pasting this uncommented version:

    docker run \
      --rm \
      -u root \
      -p 8080:8080\
      -v jenkins-data:/var/jenkins_home \
      -v /var/run/docker.sock:/var/run/docker.sock \
      -v "$HOME":/home\
      jenkinsci/blueocean
  3. Continue with the installation wizard.

on windows system

  1. Open a command prompt window.

  2. Use the following docker run command to run the jenkinsci/blueocean image as a container in Docker (remember, this command will download it automatically if there is no image locally):

    docker run ^
      --rm ^
      -u root ^
      -p 8080:8080^
      -v jenkins-data:/var/jenkins_home^
      -v /var/run/docker.sock:/var/run/docker.sock ^
      -v "%HOMEPATH%":/home^
      jenkinsci/blueocean

    For an explanation of these options, refer to the macOS and Linux instructions above.

  3. Continue with the installation wizard.

Access the Jenkins/Blue Ocean Docker container

If you have some experience with Docker and want or need to use the docker exec command to access the Jenkins/Blue Ocean Docker container through a terminal/command prompt, you can add options such as --name jenkins-tutorials (with docker run above), this will give the Jenkins/Blue Ocean Docker container the name “jenkins-tutorials”.

This means you can access the Jenkins/Blue Ocean container (through a separate terminal/command prompt window) via the docker exec command, for example:

docker exec -it jenkins-tutorials bash

installation guide

Before you can access Jenkins, you need to perform some quick “one-off” steps.

Unlock Jenkins

When you access a new Jenkins instance for the first time, you are asked to unlock it using an auto-generated password.

  1. When two sets of asterisks appear in the terminal/command prompt window, browse to http://localhost:8080 and wait for the Unlock Jenkins page to appear.

  2. From the Terminal/Command Prompt window again, copy the auto-generated alphanumeric password (between the two sets of asterisks).

  3. On the Unlock Jenkins page, paste this password into the Administrator password field and click Continue.

Customize Jenkins with plugins

After unlocking Jenkins, the Customize Jenkins page appears.

On this page, click Install suggested plugins.

The installation wizard shows the progress of Jenkins being configured, and suggested plugins for installation. This process will take a few minutes.

Create the first admin user

Finally, Jenkins asks to create your first admin user.

  1. When the Create First Admin User page appears, specify your details in the appropriate fields and click Save and Finish.

  2. When the Jenkins is ready page appears, click Start using Jenkins.
    Notes:

    • The page may say Jenkins is almost ready! If it doesn’t, click Restart.

    • If the page does not refresh automatically after a minute, use your web browser to refresh manually.

  3. If needed, log into Jenkins and you’re ready to start using Jenkins!

Stopping and restarting Jenkins

For the remainder of this tutorial, you can stop the Jenkins/Blue Ocean Docker container by typing Ctrl-C` in a Terminal/Command Prompt window, from which you can run <> `docker run ... command.

To restart the Jenkins/Blue Ocean Docker container:

  1. Run the same docker run ... command above on macOS, Linux or Windows.
    Note: This process will update the jenkinsci/blueocean Docker image if an update is available.

  2. Browse to `http://localhost:8080`.

  3. Wait until the login page appears and log in.

Fork and clone the GitHub example repository

By forking the sample warehouse where the application source code is located into your own Github account and cloning it locally, you can get a “Hello world!” simple Java application.

  1. Make sure you are logged into your GitHub account. If you don’t have a GitHub account yet, you can sign up for one for free on the GitHub website.

  2. Fork the example repository simple-java-maven-app into your account’s Github repository. If you need help along the way, please refer to the Fork A Repo documentation.

  3. Clone the simple-java-maven-app repository in your GitHub account to your local machine. Complete one of the following steps, depending on your situation (where is your operating system user account name):

    • If your machine has Github Desktop installed:

      1. On the GitHub website, click the green Clone or download button, then click Open in Desktop.

      2. In Github Desktop, before clicking the Clone button on the Clone a Repository dialog, make sure the Local Path is configured as:

        • macOS system configuration is /Users//Documents/GitHub/simple-java-maven-app

        • Linux system configuration is /home//GitHub/simple-java-maven-app

        • Windows system configuration is C:\Users\\Documents\GitHub\simple-java-maven-app

    • Other cases:

      1. Open a terminal/command prompt, and cd into the correct directory path:

        • macOS system path is /Users//Documents/GitHub/

        • Linux system path is /home//GitHub/

        • The Windows system path is C:\Users\\Documents\GitHub\ (it is recommended to use the Git bash command line instead of the usual Microsoft command prompt)

      2. Run the following command to complete the clone of the warehouse:
        git clone https://github.com/YOUR-GITHUB-ACCOUNT-NAME/simple-java-maven-app
        where YOUR-GITHUB-ACCOUNT-NAME is the name of your Github account.

Create your pipeline project in Jenkins

  1. Go back to Jenkins, log in again if necessary, and click create new jobs under Welcome to Jenkins!
    Note: If you cannot see the above, click New Item in the upper left.

  2. In the Enter an item name field, specify a name for the new Pipeline project (eg simple-java-maven-app).

  3. Scroll down and click Pipeline, then click OK at the end of the page.

  4. ( Optional ) On the next page, fill in the Description field with a brief description of the pipeline (e.g. a simple Java application that demonstrates how to build a Maven-managed application using Jenkins entry-level pipeline for .)

  5. Click the Pipeline tab at the top of the page and scroll down to the Pipeline section.

  6. In the Definition field, select the Pipeline script from SCM option. This option instructs Jenkins to fetch your pipeline from the source code management (SCM) repository, where the repository is the local Git repository you cloned.

  7. In the SCM field, select Git.

  8. In the Repository URL field, fill in the directory path of your local repository, which is mapped from the home directory of your user account on the host to the /home directory of the Jenkins container:

    • MacOS system – /home/Documents/GitHub/simple-java-maven-app

    • Linux system – /home/GitHub/simple-java-maven-app

    • Windows system – /home/Documents/GitHub/simple-java-maven-app

  9. Click Save to save your pipeline project. You can now start creating your Jenkinsfile which will be added to your local repository.

Create your initial pipeline as a Jenkinsfile

Now you are ready to create your pipeline which will automatically build your Java application using Maven in Jenkins. Your pipeline will be created as a Jenkinsfile, which will be committed to your local Git repository (simple-java-maven-app).

This is the basis of “Pipeline-as-Code”, which treats continuous delivery pipelines as part of the application, versioned and reviewed like any other code. Read more about Pipelines, and the Using Jenkinsfile chapter in the user manual.

First, create an initial pipeline to download a Maven Docker image and run it as a Docker container (this will build your simple Java application). Also add a “build” stage to the pipeline that coordinates the whole process.

  1. Using your favorite text editor or IDE, create and save a Jenkinsfile in the root directory of your local simple-java-maven-app Git repository text file.

  2. Copy and paste the following declarative pipeline code into the Jenkinsfile file:

    pipeline {
        agent {
            docker {
                image 'maven:3-alpine'
                args '-v /root/.m2:/root/.m2'
            }
        }
        stages {
            stage('Build') {
                steps {
                    sh 'mvn -B -DskipTests clean package'
                }
            }
        }
    }
    The image parameter here (refer to the docker parameter in the agent chapter) is used to download maven :3-apline the Docker image (if your machine has not downloaded it) and run the image as a separate container. this means:

    • You will run separate Jenkins and Maven containers locally in Docker.

    • The Maven container becomes the agent that Jenkins uses to run your pipeline projects. This container is short-lived – its lifetime is only the execution time of your pipeline.

    The args parameter here is in /root/ of the temporarily deployed Maven Docker container A mutual mapping is created between the .m2 (i.e. Maven repository) directory and the corresponding directory on the Docker host file system. The implementation details behind this are beyond the scope of this tutorial and are not explained here. However, the main reason for this is so that the artifacts needed to build a Java application (which Maven downloads during Pipeline execution) can remain in the Maven repository after the lifecycle of the Maven container has ended. This avoids Maven repeatedly downloading the same artifact during subsequent pipeline executions. Note that unlike the Docker data volume you created for jenkins-data , the Docker host’s filesystem is cleared every time Docker is restarted. This means that every time Docker restarts, the downloaded Maven repository artifacts are lost.
    Defines a stage called Build, which will then appear on the Jenkins UI.
    The sh step here (see steps section) runs Maven commands to cleanly build your Java application (without running any tests).
  3. Save the changes to Jenkinsfile and commit them to your local simple-java-maven-app Git repository. For example, in the simple-java-maven-app directory, run the following command:
    git add .
    keep running
    git commit -m "Add initial Jenkinsfile"

  4. Go back to Jenkins again, log in again if necessary, and click Open Blue Ocean on the left to enter the Blue Ocean interface of Jenkins.

  5. In the This job has not been run message box, click Run, then quickly click the OPEN link that appears in the lower right corner and watch Jenkins run your job pipeline project. If you can’t click on the OPEN link, click on the line on the Blue Ocean main screen to use this feature.
    Note: You may need a few minutes for the first run to complete. After cloning your local simple-java-maven-app Git repository, Jenkins then does the following:

    1. Queues items to be run on the agent.

    2. Download the Maven Docker image and run it in a container in Docker.

    3. Runs the Build phase (defined in the Jenkinsfile ) in a Maven container. During this time, Maven will download the artifacts needed to build your Java application, and these artifacts will eventually be stored in Jenkins’ local Maven repository (Docker’s host file system).

    If Jenkins has successfully built your Java application, the Blue Ocean interface will turn green.

  6. Click the X on the upper right to return to the main interface of Blue Ocean.

Add a test stage to your pipeline

  1. Back in your text editor/IDE, open your Jenkinsfile.

  2. Copy the following declarative pipeline code and paste it below the Build stage in the Jenkinsfile:

     stage('Test') {
                steps {
                    sh 'mvn test'
                }
                post {
                    always {
                        junit 'target/surefire-reports/*.xml'
                    }
                }
            }

    The final code is:

    pipeline {
        agent {
            docker {
                image 'maven:3-alpine'
                args '-v /root/.m2:/root/.m2'
            }
        }
        stages {
            stage('Build') {
                steps {
                    sh 'mvn -B -DskipTests clean package'
                }
            }
            stage('Test') {
                steps {
                    sh 'mvn test'
                }
                post {
                    always {
                        junit 'target/surefire-reports/*.xml'
                    }
                }
            }
        }
    }
    defines a stage named Test, which will then appear on the Jenkins UI.
    The sh step here (refer to the steps chapter) executes Maven commands to run your Java application’s unit tests. This command also generates a JUnit XML report, saved in the target/surefire-reports directory (located in the Jenkins container at /var/jenkins_home/workspace/simple-java-maven-app directory).
    The junit step here (provided by the JUnit Plugin) is used to archive the JUnit XML report (provided by the above mvn test command generation) and expose the results through the Jenkins interface. In Blue Ocean, the results can be obtained from the Tests page of the pipeline run. The always condition of the post chapter includes this junit step, which ensures that this step always is in the Test phase >After is executed, regardless of the result of the phase.
  3. Save the changes to Jenkinsfile and commit them to your local simple-java-maven-app Git repository. For example, in the simple-java-maven-app directory, run the following command:
    git stage .
    keep running
    git commit -m "Add 'Test' stage"

  4. Go back to Jenkins again, log back in if necessary, and go to the Jenkins Blue Ocean interface.

  5. Click Run in the upper left and then quickly click the OPEN link that appears in the lower right to watch Jenkins run your modified pipeline project. If you cannot click the OPEN link, click the top line of the Blue Ocean main interface to use this feature.
    Note: You will find that you no longer need to download the Maven Docker image to run Jenkins this time. Jenkins just needs to run a new container from the previously downloaded Maven image. Also, if Docker has not been restarted since the last Pipeline run, there is no need to download Maven artifacts during the “Build” phase. As a result, your pipeline runs faster again.
    If your modified pipeline runs successfully, the Blue Ocean interface will look like this. Note the added “Test” phase. You can click on the previous “Build” stage to get the stage output.

  6. Click the X on the upper right to return to the main interface of Blue Ocean.

Add a deliver stage to your pipeline

  1. Back in your text editor/IDE, open your Jenkinsfile.

  2. Copy the following declarative pipeline code and paste it below the Test stage in the Jenkinsfile :

     stage('Deliver') {
                steps {
                    sh './jenkins/scripts/deliver.sh'
                }
            }

    The final code is:

    pipeline {
        agent {
            docker {
                image 'maven:3-alpine'
                args '-v /root/.m2:/root/.m2'
            }
        }
        stages {
            stage('Build') {
                steps {
                    sh 'mvn -B -DskipTests clean package'
                }
            }
            stage('Test') {
                steps {
                    sh 'mvn test'
                }
                post {
                    always {
                        junit 'target/surefire-reports/*.xml'
                    }
                }
            }
            stage('Deliver') {
                steps {
                    sh './jenkins/scripts/deliver.sh'
                }
            }
        }
    }
    defines a stage named Deliver, which will then appear on the Jenkins UI.
    The sh step here (refer to the steps chapter) executes the shell script located in the jenkins/scripts directory deliver.sh, the directory is located in the root directory of the simple-java-maven-app warehouse. The actions of the deliver.sh file are included in its own text content. The general principle is to keep your pipeline code (i.e. Jenkinsfile) as concise as possible, and put more complex build steps in multiple independent shell scripts (especially for those that contain more than 2 stages of steps). This ultimately makes it easier to maintain your pipeline code, especially as your pipeline grows in complexity.
  3. Save the changes to Jenkinsfile and commit them to your local simple-java-maven-app Git repository. For example, in the simple-java-maven-app directory, run the following command:
    git stage .
    keep running
    git commit -m "Add 'Deliver' stage"

  4. Go back to Jenkins again, log back in if necessary, and go to the Jenkins Blue Ocean interface.

  5. Click Run in the upper left and then quickly click the OPEN link that appears in the lower right to watch Jenkins run your modified pipeline project. If you cannot click the OPEN link, click the top line of the Blue Ocean main interface to use this feature.
    If your modified pipeline runs successfully, the Blue Ocean interface will look like this. Note the added “Deliver” stage. You can click on previous “Test” and “Build” stages to get stage output.

    Here is what the output of the “Deliver” stage should look like, showing you what the final Java application will look like.

  6. Click X on the upper right to return to the main interface of Blue Ocean, and the list shows the historical running records of the pipeline, arranged in reverse chronological order.

Summary

well done! You just built a simple Java application with Maven using Jenkins!

The “Build”, “Test” and “Deliver” stages you created above are the basis for building more complex Java applications using Maven in Jenkins, as well as integrating Java and Maven applications with other technology stacks program.

Because Jenkins is extremely scalable, it can be modified and configured to handle almost any aspect of build orchestration and automation.

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge Java skill tree Java overviewMaven basics 118932 people are studying systematically