Jenkinsfile Example: Build, Test, Dockerize and Deploy Pipeline (2026)

Jenkinsfile example with Build, Test, Docker and Deploy stages

Quick answer: a Jenkinsfile is a text file in your repository that describes your CI/CD pipeline. Below is a complete Declarative Pipeline example that checks out code, builds, runs tests, builds a Docker image, pushes it to Docker Hub, waits for approval and deploys to Kubernetes. You can copy it, replace the image name and credentials IDs, and run it as a Multibranch Pipeline.

If you are new to Jenkins, start with our Jenkins CI/CD tool guide first, then come back here for a real pipeline.

What you need before you start

  • Jenkins running on Java 21 or newer. Java 21 and Java 25 are supported, and Java 17 is no longer supported. See the official Jenkins Java support policy.
  • Docker installed on the agent that runs the build, and the Jenkins user allowed to use it.
  • Git repository with a Dockerfile and a Jenkinsfile in the root.
  • Jenkins credentials for Docker Hub (type Username with password, ID dockerhub-credentials) and for your cluster (type Secret file, ID kubeconfig).
  • Plugins: Pipeline, Git, Credentials Binding, JUnit and Workspace Cleanup (for cleanWs()).

Complete Jenkinsfile example (Declarative Pipeline)

This example uses a Node.js app, but you can replace the npm commands with Maven, Gradle, pip or any other build tool.

pipeline {
    agent any

    options {
        timestamps()
        timeout(time: 30, unit: 'MINUTES')
        disableConcurrentBuilds()
    }

    environment {
        IMAGE_NAME = 'yourdockerhubuser/demo-app'
        IMAGE_TAG  = "build-${env.BUILD_NUMBER}"
    }

    stages {
        stage('Checkout') {
            steps {
                checkout scm
            }
        }

        stage('Build') {
            steps {
                sh 'npm ci'
            }
        }

        stage('Test') {
            steps {
                sh 'npm test'
            }
            post {
                always {
                    junit allowEmptyResults: true, testResults: 'reports/junit.xml'
                }
            }
        }

        stage('Docker Build') {
            steps {
                sh 'docker build -t $IMAGE_NAME:$IMAGE_TAG .'
            }
        }

        stage('Docker Push') {
            when { branch 'main' }
            steps {
                withCredentials([usernamePassword(
                    credentialsId: 'dockerhub-credentials',
                    usernameVariable: 'DOCKER_USER',
                    passwordVariable: 'DOCKER_PASS')]) {
                    sh '''
                        echo "$DOCKER_PASS" | docker login -u "$DOCKER_USER" --password-stdin
                        docker push $IMAGE_NAME:$IMAGE_TAG
                    '''
                }
            }
        }

        stage('Approve Deploy') {
            when { branch 'main' }
            input {
                message 'Deploy this build to production?'
                ok 'Deploy'
            }
            steps {
                echo 'Deployment approved'
            }
        }

        stage('Deploy to Kubernetes') {
            when { branch 'main' }
            steps {
                withCredentials([file(credentialsId: 'kubeconfig', variable: 'KUBECONFIG')]) {
                    sh 'kubectl set image deployment/demo-app demo-app=$IMAGE_NAME:$IMAGE_TAG'
                    sh 'kubectl rollout status deployment/demo-app --timeout=120s'
                }
            }
        }
    }

    post {
        always {
            sh 'docker logout || true'
            cleanWs()
        }
        success {
            echo 'Pipeline finished successfully'
        }
        failure {
            echo 'Pipeline failed, check the console output'
        }
    }
}

How the Jenkinsfile works, stage by stage

agent and options

agent any tells Jenkins to run the pipeline on any available agent. In options, timeout stops a stuck build after 30 minutes, timestamps() adds times to the console log, and disableConcurrentBuilds() prevents two deployments from running at once.

environment

The environment block creates variables for every stage. The image tag uses BUILD_NUMBER, so every build produces a unique, traceable image instead of overwriting latest.

Checkout, Build and Test

checkout scm clones the same repository and branch that triggered the job. The test stage publishes results with junit inside a post { always } block, so you still see test reports when tests fail.

Docker Build and Docker Push

The image is built on every branch, but it is pushed only when the branch is main, using when { branch 'main' }. Credentials are loaded with withCredentials, and the password is sent through --password-stdin so it does not appear in the process list. Jenkins also masks credential values in the console output.

Approve Deploy

The input directive pauses the pipeline and asks a person to approve the production deployment. It is a simple safety gate and it can be removed for non-production environments.

Deploy to Kubernetes

kubectl set image points the deployment to the new image, and kubectl rollout status waits until the rollout succeeds. If the rollout fails or times out, the stage fails and Jenkins marks the build as failed.

post

The final post block always logs out of Docker and cleans the workspace, so one build cannot leak credentials or files into the next one.

How to run this Jenkinsfile

  1. Commit the Jenkinsfile and Dockerfile to the root of your repository.
  2. In Jenkins, click New Item, choose Multibranch Pipeline and give it a name.
  3. Under Branch Sources, add your Git repository and the credentials to access it.
  4. Save the job. Jenkins scans the repository and creates a pipeline for every branch that has a Jenkinsfile.
  5. Open the main branch and click Build Now, then watch the stages in Pipeline Overview or in the console output.

Use a Multibranch Pipeline because the when { branch 'main' } condition only works there. In a plain Pipeline job, the branch name is not available.

Run tests in parallel to save time

If you have several independent test suites, run them in parallel to shorten the build:

stage('Test') {
    parallel {
        stage('Unit tests') {
            steps { sh 'npm run test:unit' }
        }
        stage('Lint') {
            steps { sh 'npm run lint' }
        }
    }
}

Common Jenkinsfile errors and fixes

ErrorLikely causeFix
permission denied while trying to connect to the Docker daemon socketThe Jenkins user cannot access DockerAdd the agent user to the docker group and restart the agent
script returned exit code 127Command not found on the agent (for example npm, docker or kubectl)Install the tool on the agent or use a Docker agent that includes it
when { branch 'main' } stage is always skippedJob is not a Multibranch PipelineCreate a Multibranch Pipeline job
No such DSL method 'cleanWs'Workspace Cleanup plugin is missingInstall the Workspace Cleanup plugin
Could not find credentials entry with IDThe credentials ID in the Jenkinsfile does not match JenkinsCheck the ID in Manage Jenkins, Credentials

Security tips for Jenkins pipelines

  • Never hard-code passwords, tokens or kubeconfig files in a Jenkinsfile.
  • Give each credential only the permissions it needs, for example a registry token that can push to one repository.
  • Limit who can edit Jenkinsfiles on the main branch, because anyone who can change the pipeline can use its credentials.
  • Remember that access to the Docker socket is effectively root access on the agent.
  • Keep Jenkins and its plugins updated. The official Jenkinsfile documentation is the best place to check syntax for your version.

Declarative vs Scripted Pipeline: which one should you use?

Jenkins supports two syntaxes. The example above uses Declarative Pipeline, which has a fixed structure that Jenkins can validate before the job runs. Scripted Pipeline is plain Groovy inside a node { } block and gives you full programming freedom.

FeatureDeclarativeScripted
Starts withpipeline { }node { }
Learning curveEasier, structuredSteeper, needs Groovy knowledge
Syntax checkingValidated before the runErrors appear at runtime
Built-in featureswhen, post, input, parametersYou write them with if/else and try/catch
Best forMost teams and projectsComplex logic and dynamic stages

Here is the same idea written as a small Scripted Pipeline, so you can see the difference:

node {
    try {
        stage('Checkout') {
            checkout scm
        }
        stage('Build') {
            sh 'npm ci'
        }
        stage('Test') {
            sh 'npm test'
        }
        currentBuild.result = 'SUCCESS'
    } catch (err) {
        currentBuild.result = 'FAILURE'
        throw err
    } finally {
        cleanWs()
    }
}

Start with Declarative. You can still drop into Groovy inside a script { } block when you need a loop or a condition that Declarative does not support.

Run each stage inside a Docker container

Instead of installing Node, Maven or Python on every Jenkins agent, you can run a stage inside a container. The build then uses the same tool version every time, on every machine. This needs the Docker Pipeline plugin and Docker on the agent.

pipeline {
    agent {
        docker {
            image 'node:20-alpine'
            args '-u root:root'
        }
    }
    stages {
        stage('Build and test') {
            steps {
                sh 'npm ci'
                sh 'npm test'
            }
        }
    }
}

For a Java project, switch the image to a Maven image that includes the JDK you need, for example maven:3.9-eclipse-temurin-21, and run sh 'mvn -B clean verify'. Pin the image version instead of using latest, so a new image does not break your build overnight.

Start the pipeline automatically with triggers

A pipeline that someone must start by hand is not continuous integration. You have three common options:

  • Webhook (best): GitHub, GitLab or Bitbucket calls Jenkins when code is pushed. Builds start within seconds and Jenkins does no polling.
  • pollSCM: Jenkins checks the repository on a schedule. It works behind a firewall but wastes resources.
  • cron: Runs on a schedule regardless of changes, which is good for nightly builds.
pipeline {
    agent any
    triggers {
        pollSCM('H/5 * * * *')   // check Git every 5 minutes
        // cron('H 2 * * *')      // or run nightly around 2 AM
    }
    stages {
        stage('Build') { steps { sh 'npm ci' } }
    }
}

The H symbol lets Jenkins spread the start time, which prevents all jobs from running at the exact same minute.

Add parameters to choose the environment

Parameters let a person pick options when they start a build, for example staging or production:

pipeline {
    agent any
    parameters {
        choice(name: 'TARGET_ENV', choices: ['staging', 'production'], description: 'Where to deploy')
        booleanParam(name: 'RUN_TESTS', defaultValue: true, description: 'Run the test suite')
    }
    stages {
        stage('Test') {
            when { expression { params.RUN_TESTS } }
            steps { sh 'npm test' }
        }
        stage('Deploy') {
            steps {
                echo "Deploying to ${params.TARGET_ENV}"
            }
        }
    }
}

Save build files with archiveArtifacts

Build outputs such as a JAR, a ZIP, a coverage report or an SBOM can be stored with the build, so people can download them from the Jenkins page later:

post {
    success {
        archiveArtifacts artifacts: 'dist/**,coverage/**', fingerprint: true
    }
}

Scan the Docker image before you push it

A pipeline that deploys a vulnerable image faster is not an improvement. Add a scan stage between build and push. The example below uses the open-source Trivy scanner and fails the build when it finds high or critical issues:

stage('Image Scan') {
    steps {
        sh 'trivy image --exit-code 1 --severity HIGH,CRITICAL $IMAGE_NAME:$IMAGE_TAG'
    }
}

Install the scanner on the agent first. If your project already has many known issues, begin with --exit-code 0 so the scan only reports, then switch to blocking once the backlog is fixed.

Handle failures, retries and rollbacks

Real pipelines fail for reasons that have nothing to do with your code: a flaky network, a slow registry, a temporary DNS error. Three small tools help:

  • retry(3) { ... } repeats a step up to three times, which is useful for downloads and pushes.
  • timeout(time: 10, unit: 'MINUTES') { ... } stops a step that hangs.
  • catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE') { ... } marks a stage as failed but lets the pipeline continue, for optional checks.

For deployments, add an automatic rollback. If kubectl rollout status fails, undo the last release:

stage('Deploy to Kubernetes') {
    steps {
        withCredentials([file(credentialsId: 'kubeconfig', variable: 'KUBECONFIG')]) {
            sh 'kubectl set image deployment/demo-app demo-app=$IMAGE_NAME:$IMAGE_TAG'
            script {
                try {
                    sh 'kubectl rollout status deployment/demo-app --timeout=120s'
                } catch (err) {
                    sh 'kubectl rollout undo deployment/demo-app'
                    error('Deployment failed and was rolled back')
                }
            }
        }
    }
}

Send notifications when a build fails

Nobody should have to watch the console. Use the post section to alert your team. With the Slack Notification plugin, for example:

post {
    failure {
        slackSend channel: '#builds',
                  color: 'danger',
                  message: "FAILED: ${env.JOB_NAME} #${env.BUILD_NUMBER} (${env.BUILD_URL})"
    }
}

You can also use the built-in mail step if your Jenkins server has SMTP configured. Keep messages short and always include the job name, build number and a link to the console output.

Reuse code with Shared Libraries

When you have ten repositories that all use the same build, scan and deploy stages, copying a Jenkinsfile ten times becomes painful. A Jenkins Shared Library stores common steps in one Git repository, and each Jenkinsfile imports it:

@Library('company-pipeline-lib') _

dockerPipeline(
    imageName: 'yourdockerhubuser/demo-app',
    deployTarget: 'demo-app'
)

Configure the library under Manage Jenkins, then System, then Global Trusted Pipeline Libraries. Version it with Git tags so a change to the library cannot break every pipeline at once.

Validate your Jenkinsfile before you commit

You do not have to push and pray. Jenkins can check Declarative syntax for you:

  • Use the Pipeline Syntax snippet generator and the Declarative Directive Generator (link in any Pipeline job’s sidebar) to build correct code.
  • Use Replay on a past build to edit and re-run a Jenkinsfile without committing.
  • Run the linter from the command line:
curl -X POST -u USER:API_TOKEN -F "jenkinsfile=<Jenkinsfile" \
  https://your-jenkins.example.com/pipeline-model-converter/validate

If the file is valid, Jenkins answers Jenkinsfile successfully validated. Otherwise it points to the line with the problem.

Jenkinsfile best practices

  • Keep the Jenkinsfile in the repository root and review changes to it like any other code.
  • Do not use latest tags for your own images. Tag with the build number or Git commit SHA.
  • Pin versions of build images and plugins.
  • Keep steps small. Put long shell logic into scripts in your repo and call them from the Jenkinsfile.
  • Fail fast. Run quick checks (lint, unit tests) before slow ones (integration tests, image scans).
  • Use post cleanup so workspaces and Docker logins never leak between builds.
  • Use agents with labels (for example agent { label 'docker' }) so the right jobs run on the right machines, and avoid running builds on the controller.
  • Limit access. Give each credential only the permissions it needs.

Frequently asked questions

What is a Jenkinsfile?

A Jenkinsfile is a text file, stored in your Git repository, that defines your Jenkins pipeline as code. It lists the stages (such as build, test and deploy) and the steps inside each stage, so your CI/CD process is versioned and reviewed like any other code.

What is the difference between Declarative and Scripted Pipeline?

Declarative Pipeline uses a structured pipeline { } block with fixed sections like agent, stages and post, which is easier to read and validate. Scripted Pipeline is full Groovy code and is more flexible but harder to maintain. Jenkins recommends starting with Declarative Pipeline.

Where should I store Docker Hub passwords in a Jenkinsfile?

Never write them in the Jenkinsfile. Store them in Jenkins Credentials and load them with withCredentials or the credentials() helper. Jenkins then masks the values in the console log.

Why does my Jenkins build say “permission denied” for Docker?

The user that runs your Jenkins agent cannot access the Docker socket. Add that user to the docker group on the agent machine, restart the agent, and run the build again. Treat docker group access as root-level access and limit who can edit pipelines.

Why does the “when { branch }” condition not work?

The branch condition only works in a Multibranch Pipeline job. In a plain Pipeline job there is no branch name, so use a Multibranch Pipeline or compare env.GIT_BRANCH instead.

Which Java version do I need to run Jenkins?

Current Jenkins releases require Java 21 or newer. Java 21 and Java 25 are supported, while Java 17 reached the end of support in 2026.

Conclusion

A good Jenkinsfile is short, readable and safe: it builds on every commit, tests before it packages, deploys only from the main branch, keeps secrets in Jenkins credentials and cleans up after itself. Start with the example above, test it on a sample project, and then adapt the stages to your own application.

Found this guide helpful? Share with your peers

Help fellow engineers, students, and professionals discover this resource.

1-Click Viral Share

Leave a Comment

Your email address will not be published. Required fields are marked *