Medium java docker

How do you create a Jenkins pipeline for a Java application?

The 30 second answer

I put a Jenkinsfile in the repo and use a Pipeline that checks out the code, sets up the JDK, runs the Maven or Gradle build and tests, publishes the artifact, and only then builds and pushes a container image. Stages are explicit, test failures fail the pipeline, and I keep credentials in Jenkins credentials, not in the Jenkinsfile. A Declarative Pipeline is the form I would write first because it is easier to read and to review.

Could you say this in an interview?

Jenkins Pipeline is documented as code: a Jenkinsfile lives with the application and describes stages. I prefer Declarative Pipeline for application CI.

A typical Java flow:

  1. Check out the commit being built.
  2. Use a JDK tool (Temurin 21, for example) and run ./mvnw -B verify or ./gradlew check. The wrapper keeps the build tool version in the repo.
  3. Publish the test report and the artifact (Nexus, Artifactory, or GitHub Packages).
  4. On the main branch, build a container image and push it, tagged with the git sha.
  5. Optionally deploy to a staging environment. Production is a separate, approved stage or a different CD system.

I do not put passwords or signing keys in the Jenkinsfile. I use credentials() and I do not run the build as root on a long-lived dirty agent when a clean container agent is available.

// Jenkinsfile
pipeline {
  agent any
  tools { jdk 'temurin-21' }
  stages {
    stage('Verify') {
      steps { sh './mvnw -B verify' }
    }
    stage('Image') {
      when { branch 'main' }
      steps { sh 'docker build -t registry.example/checkout:$GIT_COMMIT .' }
    }
  }
  post {
    always { junit 'target/surefire-reports/*.xml' }
  }
}
Sources (3)
  1. Jenkins: Pipelinejenkins.io
  2. Jenkins: Declarative Pipelinejenkins.io
  3. Jenkins: Handling credentialsjenkins.io