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.
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:
- Check out the commit being built.
- Use a JDK tool (Temurin 21, for example) and run
./mvnw -B verifyor./gradlew check. The wrapper keeps the build tool version in the repo. - Publish the test report and the artifact (Nexus, Artifactory, or GitHub Packages).
- On the main branch, build a container image and push it, tagged with the git sha.
- 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)
- Jenkins: Pipelinejenkins.io
- Jenkins: Declarative Pipelinejenkins.io
- Jenkins: Handling credentialsjenkins.io