A Jenkinsfile is a text file that describes your entire delivery pipeline as code. Build, test, scan, deploy: every step lives in the file, versioned alongside the application it ships. When a deploy fails at 2 a.m., nobody has to remember which buttons someone clicked in a web interface six months ago. The pipeline is in the repository, it is readable, and it can be reviewed like any other code.
This guide teaches the declarative Pipeline syntax, which is the structured, opinionated way to write a Jenkinsfile. Jenkins also offers scripted Pipeline, a more flexible Groovy-based syntax, but declarative is the right default for almost every team: it is easier to read, easier to validate, and Jenkins can check its syntax before the pipeline runs. Everything here is tested against Jenkins LTS 2.580.3, released on 25 November 2026, which requires Java 21 or 25 to run the controller. If you are new to Jenkins itself, start with our Jenkins CI/CD pipeline tutorial, which covers installation and your first freestyle job, then come back here.
By the end of this guide you will have a complete Jenkinsfile for a real application: it checks out code, builds it, runs tests, builds a Docker image, scans it, and deploys it, with notifications and cleanup. You will also understand parameters, credentials, parallel stages, post actions and shared libraries, which are the tools that turn a simple pipeline into one a whole team can rely on.
What a Jenkinsfile Is and How Declarative Pipeline Works
A Jenkinsfile is a file named Jenkinsfile, stored in the root of a repository, that defines a Pipeline. When Jenkins builds a project that uses Pipeline as code, it reads the Jenkinsfile from the repository, either from the branch being built or from a branch you specify, and executes it. The pipeline runs on agents, which are machines that execute the steps, and the controller orchestrates the run, shows the results, and stores the logs.
Declarative Pipeline has a fixed structure. The whole file is a pipeline block. Inside it, an agent section says where the pipeline runs. An environment section sets variables. A stages section holds one or more stage blocks, and each stage holds a steps block with the actual commands. Options, triggers, parameters, tools and post sections add behaviour around the stages. That structure is enforced by Jenkins: if the file does not follow it, the pipeline fails validation before it runs anything, which catches mistakes early.
The fixed structure is a feature, not a limitation. Because every declarative pipeline has the same shape, any engineer can read any pipeline in the organisation and understand it in minutes. Because the structure is validated, a typo in a stage name fails fast instead of failing halfway through a deploy. And because the structure is declarative, Jenkins can render the pipeline visually in the Blue Ocean interface or the Pipeline graph view, showing each stage as a box that turns green or red as it runs. That visual feedback is genuinely useful during an incident: you can see exactly which stage failed without reading logs first.
To use a Jenkinsfile, create a Pipeline job in Jenkins and point it at your repository. The most common setup is a Multibranch Pipeline, which scans the repository, finds every branch with a Jenkinsfile, and creates a job for each one. Pull requests get their own builds automatically, which means every change is tested before it merges. For a single-branch project, a plain Pipeline job with the definition set to "Pipeline script from SCM" works fine. Either way, the Jenkinsfile is the source of truth, and Jenkins reads it from the repository on every run.
One decision to make early is where the pipeline runs. The agent directive controls this. agent any runs on any available agent, which is fine for learning. In production you will usually label your agents, for example agent { label 'docker' } to run on agents with Docker installed, or use a Docker agent to run the whole pipeline inside a container. Agent choice matters because the tools available, the network access, and the credentials installed all depend on which machine runs the steps. If a step fails with "command not found", the first thing to check is whether the agent it ran on actually has that tool.
Your First Jenkinsfile: Build, Test and Report
Here is a complete Jenkinsfile for a Node.js application. It is short enough to read in one sitting and complete enough to use as a starting point for a real project. Read it first, then the explanation below walks through every section.
pipeline { agent any tools { nodejs 'node-20' } environment { APP_NAME = 'shop-api' NODE_ENV = 'test' } stages { stage('Checkout') { steps { checkout scm } } stage('Install') { steps { sh 'npm ci' } } stage('Test') { steps { sh 'npm test' } } stage('Build') { steps { sh 'npm run build' } } } post { always { junit 'test-results/**/*.xml' archiveArtifacts artifacts: 'dist/**/*', fingerprint: true } success { echo 'Build passed.' } failure { echo 'Build failed. Check the Test stage first.' } } } The tools section tells Jenkins to make a named tool installation available on the agent. nodejs 'node-20' refers to a Node.js installation configured in Jenkins under Manage Jenkins, then Tools. The name must match exactly, including case, or the pipeline fails at startup with a clear error. Tools configured this way are installed automatically on the agent if they are not already there, which makes agents reproducible without baking every tool into every image.
The environment section sets variables that are available to every step in the pipeline. APP_NAME and NODE_ENV here are simple strings, but environment variables can also come from credentials, which the credentials section of this guide covers. Environment variables set here are visible in the build log only if a step prints them, so do not put secrets in this section.
Each stage is a named unit of work. The stage name appears in the Pipeline graph view, so name stages for the reader, not for the machine: "Test" and "Build" are good names. "Stage 3" is not. The steps block holds the actual work, usually shell commands with sh, but also Pipeline steps such as echo, checkout and archiveArtifacts.
The post section runs after all stages finish, and the condition decides when each block runs. always runs every time, which is where test reporting and artifact archiving belong, because you want the test results even when the build fails. success runs only when the build passed, and failure runs only when it failed. Other conditions include unstable for builds that passed with test failures, changed for builds whose result differs from the previous one, and cleanup, which runs last and is the right place for workspace cleanup. The junit step publishes test results so Jenkins shows a test trend and a list of failing tests, which is far more useful than a log line saying tests failed.
Save this file as Jenkinsfile in a repository, create a Pipeline job, and run it. The first run will probably fail, and that is normal. Read the error, fix the cause, and run it again. The fastest way to learn Jenkinsfile syntax is to break a pipeline and read the error message, because Jenkins errors usually name the exact line and the exact problem.
Stages, Steps, Agents and When Conditions
Stages can do more than run in sequence. They can run in parallel, they can run only when a condition is met, and they can use a different agent from the rest of the pipeline. These three features cover most of the real-world pipeline designs you will meet.
Parallel stages run at the same time, which shortens the build when stages do not depend on each other. Linting, unit tests and a security scan can all run in parallel, because none of them needs the others to finish first. The syntax nests stages inside a parallel block.
stage('Quality checks') { parallel { stage('Lint') { steps { sh 'npm run lint' } } stage('Unit tests') { steps { sh 'npm test' } } stage('Security scan') { steps { sh 'npm audit --audit-level=high' } } } } Be careful with parallel stages that share state. Two stages that both write to the same directory or the same database will interfere with each other in ways that are hard to reproduce. Parallel stages should be independent: each one works on its own files, or reads shared files without writing to them. If two stages need the same resource, run them in sequence instead. A build that is five minutes faster but fails randomly is not faster.
The when directive controls whether a stage runs at all. The most common conditions are branch-based: deploy only from the main branch, run a heavy end-to-end suite only on pull requests, or skip a slow stage on feature branches. The directive supports branch names, environment variables, change requests, and expressions that evaluate Groovy code.
stage('Deploy to staging') { when { branch 'main' } steps { sh './deploy.sh staging' } } stage('Deploy to production') { when { allOf { branch 'main' expression { params.DEPLOY_PROD == true } } } steps { sh './deploy.sh production' } } The agent directive can also be set per stage. A pipeline that mostly runs on a general agent might run its Docker build stage on an agent labelled docker, and its deploy stage on an agent with production credentials. Per-stage agents are also how you run a stage inside a container while the rest of the pipeline runs directly on the agent.
stage('Build image') { agent { docker { image 'node:20-alpine' } } steps { sh 'node --version' sh 'npm ci' } } The Docker agent pulls the image, runs the stage inside a container based on it, and removes the container when the stage finishes. This guarantees the build environment is identical every time, regardless of what is installed on the agent. It is the simplest form of reproducible builds in Jenkins, and it is the right choice when the build depends on a specific version of a tool. For the broader picture of how pipelines fit into delivery, our CI/CD pipeline explained guide covers the concepts this syntax implements.
Parameters, Environment and Credentials
A pipeline that cannot be configured without editing the Jenkinsfile is a pipeline that will be edited constantly. Parameters solve this. They let the person who starts a build choose values: which environment to deploy to, whether to run the slow test suite, or which version to build. Parameters are declared in a parameters block, and they appear as a form when the build is triggered.
parameters { choice(name: 'ENVIRONMENT', choices: ['staging', 'production'], description: 'Where to deploy') booleanParam(name: 'RUN_E2E', defaultValue: false, description: 'Run end-to-end tests') string(name: 'VERSION', defaultValue: '', description: 'Version tag to build (empty means latest)') } Use parameters inside steps as params.ENVIRONMENT and inside shell commands as ${params.ENVIRONMENT}. The production deploy example in the previous section used a boolean parameter as a safety gate: deploying to production requires someone to check the box deliberately. That pattern is worth copying. A deploy that happens because someone forgot to uncheck a box is an accident; a deploy that happens because someone checked a box is a decision.
Credentials are how a pipeline uses passwords, tokens and keys without writing them in the Jenkinsfile. Jenkins stores credentials in its credential store, each with an ID, and the pipeline refers to the ID. The withCredentials step makes the credential available as environment variables inside its block, and Jenkins masks the values in the build log so they do not leak into the output.
stage('Push image') { steps { withCredentials([usernamePassword(credentialsId: 'docker-hub', usernameVariable: 'REG_USER', passwordVariable: 'REG_PASS')]) { sh 'echo "$REG_PASS" | docker login -u "$REG_USER" --password-stdin' sh 'docker push myapp:${BUILD_NUMBER}' } } } Three rules govern credentials in pipelines. First, never write a secret in a Jenkinsfile, in an echo statement, or in a build parameter with a default value. Second, use the narrowest credential type for the job: a username and password binding for a registry, a secret text binding for a token, and an SSH key binding for Git operations. Third, give credentials descriptive IDs that say what they are for, such as docker-hub or aws-deploy, and restrict which jobs can use them through folder-scoped credentials where your Jenkins setup supports it. The official Pipeline syntax documentation lists every credential binding type and the parameters each one accepts.
Environment variables set in the environment section can also draw on credentials directly, which is cleaner when the whole pipeline needs a value rather than one stage.
environment { AWS_ACCESS_KEY_ID = credentials('aws-access-key') DOCKERHUB = credentials('docker-hub') } Be aware of one sharp edge: credentials bound this way are available to every stage, which is convenient but broad. Prefer withCredentials inside the stage that needs the secret when only one stage needs it. Least privilege applies to pipelines as much as it applies to servers.
A Complete Pipeline: Docker Build, Scan and Deploy
The Jenkinsfile below ties the pieces together into a pipeline that a small team could use in production. It checks out the code, runs quality checks in parallel, builds a Docker image, scans it, pushes it, and deploys to staging automatically and to production only when the build runs on the main branch with the deploy parameter enabled. Read it as a template and adapt the commands to your own stack.
pipeline { agent { label 'docker' } parameters { booleanParam(name: 'DEPLOY_PROD', defaultValue: false, description: 'Deploy to production') } environment { IMAGE = "myregistry/shop-api:${env.BUILD_NUMBER}" } stages { stage('Checkout') { steps { checkout scm } } stage('Quality checks') { parallel { stage('Lint') { steps { sh 'npm run lint' } } stage('Unit tests') { steps { sh 'npm test' } } } } stage('Build image') { steps { sh 'docker build -t "$IMAGE" .' } } stage('Scan image') { steps { sh 'trivy image --exit-code 1 --severity HIGH,CRITICAL "$IMAGE"' } } stage('Push image') { steps { withCredentials([usernamePassword(credentialsId: 'docker-hub', usernameVariable: 'REG_USER', passwordVariable: 'REG_PASS')]) { sh 'echo "$REG_PASS" | docker login -u "$REG_USER" --password-stdin' sh 'docker push "$IMAGE"' } } } stage('Deploy to staging') { when { branch 'main' } steps { sh './deploy.sh staging "$IMAGE"' } } stage('Deploy to production') { when { allOf { branch 'main' expression { params.DEPLOY_PROD == true } } } steps { input message: 'Deploy to production?', ok: 'Deploy' sh './deploy.sh production "$IMAGE"' } } } post { always { junit 'test-results/**/*.xml' sh 'docker rmi "$IMAGE" || true' } failure { emailext subject: "Build failed: ${env.JOB_NAME} #${env.BUILD_NUMBER}", body: "See ${env.BUILD_URL} for details.", to: 'team@example.com' } } } Three parts of this pipeline deserve attention. The scan stage uses Trivy, an open source image scanner, and fails the build on high or critical vulnerabilities. Scanning in the pipeline means a vulnerable image cannot reach production by accident. If your team does not scan images yet, this one stage is the highest-value addition you can make to any pipeline.
The production deploy stage uses the input step, which pauses the pipeline and waits for a human to approve. The build waits, the approver clicks Deploy, and the pipeline continues. The input step is the simplest form of a manual approval gate, and it is the right tool when production deploys need a human decision but the rest of the pipeline should be automatic. Set a timeout on the input step in a real pipeline, so a build that nobody approves does not wait forever and hold an executor.
The post section cleans up the Docker image from the agent, so disk space does not fill up over weeks of builds, and sends an email when the build fails. The || true after the docker rmi command means the cleanup step cannot fail the build if the image is already gone. That pattern, making cleanup steps unable to fail, is worth using everywhere: a build that passed should not turn red because its cleanup hit a snag.
Shared Libraries, Multibranch Pipelines and Troubleshooting
When every repository has its own Jenkinsfile, the same steps get copied everywhere: the same lint command, the same scan command, the same deploy script invocation. Shared libraries fix this. A shared library is a separate repository with reusable Pipeline code, usually in a vars directory, and any Jenkinsfile can call it as if it were a built-in step.
@Library('my-shared-library') _ pipeline { agent any stages { stage('Build') { steps { buildNodeApp() } } } } In this example, buildNodeApp is a step defined once in the shared library and used by every Node.js service in the organisation. When the build process changes, one change in the library updates every pipeline. That is the same argument as for any shared code, and it applies just as strongly to pipelines. Keep the library small and focused: a handful of steps that every team uses, with clear names and documentation. A library that tries to cover every case becomes a framework, and frameworks are harder to change than the duplication they replaced.
Multibranch Pipeline is the job type that makes Jenkinsfiles scale. It scans a repository, creates a job for every branch and pull request that contains a Jenkinsfile, and deletes jobs for branches that are gone. Each branch builds with its own Jenkinsfile, so a change to the pipeline in a feature branch is tested by that branch's build before it merges. Combined with the when directive, this gives you per-branch behaviour without per-branch configuration: feature branches run tests, the main branch deploys to staging, and production deploys need a parameter and an approval.
When a pipeline fails, work through the failure in order. First, read the Pipeline graph view to find which stage failed. Second, open that stage's logs and read the last lines, where the error usually is. Third, check the agent: was the tool installed, did the agent have network access, did the disk fill up? Fourth, validate the Jenkinsfile itself. Jenkins has a built-in Declarative Pipeline linter: paste the file into the Pipeline Syntax page, or use the replay feature on a failed build to edit the Jenkinsfile and run it again without committing. Replay is the fastest way to iterate on a pipeline, because it skips the commit and push cycle. The official Jenkinsfile documentation explains the linter, the replay feature and the full syntax in detail.
Common errors have recognisable signatures. "No such DSL method" means a step is misspelled or used in the wrong context, such as a step that only works inside a script block. "Expected a step" means a stage is missing its steps block. "WorkflowScript" errors with a line number point at the exact line to fix. And a pipeline that fails immediately, before any stage runs, almost always has a syntax error in the pipeline block itself, often a missing brace. Count your braces, and let your editor's Groovy support highlight them.
If you are comparing Jenkins with other CI systems, our GitHub Actions tutorial covers the equivalent concepts in GitHub's YAML-based system, which is useful context when you need to choose between the two or migrate from one to the other.
Frequently Asked Questions
What is the difference between declarative and scripted Pipeline?
Declarative Pipeline uses a fixed, structured syntax with pipeline, agent, stages and steps blocks, and Jenkins validates it before running. Scripted Pipeline is Groovy code with a node block, which is more flexible but harder to read and easier to break. Declarative is the right default for most teams, and scripted is for the rare cases where declarative cannot express what you need.
Where does the Jenkinsfile live?
In the root of your repository, next to the code it builds. Jenkins reads it from the repository on every build, which means the pipeline is versioned, reviewed and branched alongside the application. For a Multibranch Pipeline, every branch with a Jenkinsfile gets its own job automatically.
How do I use secrets in a Jenkinsfile?
Store them in the Jenkins credential store and reference them by ID with withCredentials or the credentials helper in the environment section. Jenkins masks the values in build logs. Never write a secret in the Jenkinsfile itself, in a build parameter default, or in an echo statement.
Can I test a Jenkinsfile without committing it?
Yes. Use the Replay feature on a previous build to edit the Jenkinsfile and run it again, or validate the syntax on the Pipeline Syntax page in Jenkins. Both let you iterate without pushing a commit for every change, which makes debugging a pipeline much faster.
How do I deploy only from the main branch?
Use the when directive with a branch condition on the deploy stage, as shown in this guide. Combine it with a boolean parameter and an input step for production, so deploys need both the right branch and a deliberate human decision. Feature branches then run tests without ever reaching a deployment stage.
Conclusion
A Jenkinsfile turns your delivery process from a set of manual steps into code that is versioned, reviewed and repeatable. Start with the simple pipeline from this guide, add quality checks in parallel, gate production behind a parameter and an approval, and extract the repeated steps into a shared library once you have more than one service using them. The declarative syntax rewards you for that discipline: it validates your pipeline before it runs, it renders each stage visually so failures are easy to find, and it stays readable when the pipeline grows. The next step is to take one project you currently deploy by hand and write its Jenkinsfile. When the first green build deploys itself to staging, you will have replaced a manual process with a system, and that is the whole point of CI/CD.
Sources: Verified 2 Dec 2026. Jenkins Pipeline syntax documentation: https://www.jenkins.io/doc/book/pipeline/syntax/ ; Jenkinsfile documentation: https://www.jenkins.io/doc/book/pipeline/jenkinsfile/ . Jenkins LTS 2.580.3 current (released 25 Nov 2026); controller requires Java 21 or 25. No unverified figures stated.
