What Is a Stage in Jenkins?

What Is a Stage in Jenkins?

A friendly, step-by-step guide to the named phases that turn a long list of automated chores into a clear, visible, easy-to-fix delivery pipeline.

Imagine you are building a bicycle in a factory. You do not just “make a bicycle” in one giant blob of work. First the frame is welded, then the wheels are attached, then the brakes are fitted, then an inspector checks everything, and finally the bike is packed in a box. Each of those phases has a name, a clear job, and a clear result. If the brakes fail the inspection, you know exactly which phase went wrong, and you do not have to dig through the whole factory to find the problem.

In Jenkins, those named phases are called stages. A stage is one of the most important building blocks of a Jenkins pipeline, and understanding it makes everything else about pipelines easier. In this guide you will learn what a stage is, why it exists, how it works inside Jenkins, how stages can run in order or side by side, how to control them with conditions and time limits, and what habits keep stages healthy in real projects. No earlier knowledge is needed, and every new word is explained the first time it appears.

1What Is a Stage in Jenkins?

A stage is a named block of work inside a Jenkins pipeline. It groups together a set of related steps and gives that group a clear label such as Build, Test, or Deploy.

Start with two words you may already know. A pipeline is the full assembly line that takes your code from a programmer’s laptop all the way to real users. A step is one small action, such as running a command, copying a file, or sending a message. A stage sits in the middle: it is a group of steps that together achieve one goal.

So the picture looks like this. A pipeline holds several stages. Each stage holds one or more steps. Steps do the real work, while stages give that work a shape, a name, and a place on the screen.

Everyday analogy

Think of a school day. The day is the pipeline. Morning Maths, Lunch, and Afternoon Sports are the stages. Inside Morning Maths, the small actions such as “open the book” and “solve five questions” are the steps. Because the day is divided into named blocks, everyone can say, “We are currently in Lunch,” and everyone understands the situation at a glance.

What a stage gives you

  • A name. People can talk about “the Test stage” instead of “that middle bit of the script”.
  • A visible box. Jenkins draws every stage on the job page, so anyone can see which phase is running, which finished, and which failed.
  • A boundary for control. You can set conditions, time limits, and special machines for one stage without touching the others.
  • A place to measure. Jenkins records how long each stage took, so slow phases are easy to spot.
1+
stages needed in every declarative pipeline
1+
steps needed inside every stage
4-6
typical stages in a simple delivery pipeline

2Why Stages Exist: The Problem They Solve

To see why stages matter, imagine life without them.

Before pipelines became popular, many teams used a single long job that ran one big list of commands from top to bottom. When such a job failed, the team faced a wall of thousands of log lines and had to search for the spot where things broke. Was it the compile? The tests? The upload? Nobody could tell at a glance.

That old way caused three troubles. First, it was hard to read, because the whole process was one shapeless blob. Second, it was hard to fix, because a failure gave no clue about where to look first. Third, it was hard to improve, because nobody knew which part was slow. Stages solve all three at once by chopping the blob into named, measurable pieces.

Everyday analogy

Reading a book with no chapters is exhausting. You cannot find anything, and you cannot tell how far you have come. Chapter titles let you jump straight to the part you need. Stages are the chapter titles of your pipeline.

*
Tip

A good stage name answers the question, “What is Jenkins doing right now?” Names like Build, Unit Tests, and Deploy to Staging are clear. Names like Step 3 or Misc are not.

3Core Concepts Around Stages

A few neighbouring words appear again and again when people talk about stages. Learn them together.

Whole

Pipeline

The complete assembly line from code to delivery. It contains all the stages, in order.

Group

Stage

A named phase inside the pipeline, such as Build or Test. It holds one or more steps.

Action

Step

One single task, such as running a command or archiving a file. Steps live inside stages.

Machine

Agent

The worker computer that actually runs the work. You can pick one agent for the whole pipeline or a different one for each stage.

Slot

Executor

A single work slot on an agent. A stage needs a free executor before it can run.

File

Jenkinsfile

The text file in your repository where the pipeline and its stages are written down.

Folder

Workspace

The temporary folder on the agent where code is downloaded and work happens. Stages that use the same agent share the same workspace.

Result

Artifact

A file produced by the pipeline that people want to keep, such as a finished program package.

Two styles of writing pipelines

Jenkins lets you write pipelines in two styles. Declarative is a tidy, structured layout with a fixed shape: it has a clear place for the agent, for a list of stages, and for actions to run afterwards. Scripted is a free-form style built on a real programming language called Groovy, which is more powerful but easier to make messy.

Stages exist in both styles, but they behave a little differently. In declarative style, stages are a required part of the structure, and Jenkins checks them carefully. In scripted style, a stage is simply a named block that you may place wherever you like, and it is mainly used for labelling and display. Most beginners and most teams should start with declarative style.

4Architecture: Where Stages Fit

Let us place stages inside the bigger Jenkins picture so you can see who does what.

A Jenkins system has one controller, which is the brain, and many agents, which are the hands. The controller reads the Jenkinsfile, understands the stages, keeps track of their progress, and shows the result in the web page. The agents run the real steps. When you split a pipeline into stages, the controller can hand each stage to a suitable agent and watch it carefully.

flowchart LR
  DEV["Developer"] -->|"push code"| REPO["Git Repository"]
  REPO -->|"webhook"| CTRL["Jenkins Controller"]
  CTRL -->|"reads Jenkinsfile"| PIPE{"Pipeline"}
  PIPE --> S1["Stage: Build"]
  PIPE --> S2["Stage: Test"]
  PIPE --> S3["Stage: Package"]
  PIPE --> S4["Stage: Deploy"]
  S1 -->|"runs on"| A1["Agent 1"]
  S2 -->|"runs on"| A2["Agent 2"]
  S3 -->|"runs on"| A1
  S4 -->|"runs on"| A3["Agent 3"]
  A1 --> ART["Artifact Storage"]
  CTRL -->|"shows progress"| VIEW["Stage View Screen"]
Figure 1: The controller reads the stages and hands each one to an agent, while the screen shows live progress.

Walking through the picture

A developer pushes code to the Git repository. The repository sends a small message called a webhook (an automatic “something changed!” notification over the web) to the controller. The controller reads the Jenkinsfile and finds four stages. It places each stage on a matching agent. Stage 1 and Stage 3 happen to use the same agent, so they share one workspace. Stage 2 uses another agent, perhaps because it needs special tools. The last stage runs on a third agent that is allowed to reach the real servers. Meanwhile the controller draws all of this on the Stage View screen, so people can watch.

i
Good to know

A stage is not a machine and not a folder. It is only a labelled group of steps. Where it runs is decided by the agent setting, which we will explore in a later chapter.

5The Anatomy of a Declarative Pipeline

Before we study a stage on its own, let us see where it sits in the whole structure.

A declarative pipeline has a fixed shape with a few named parts. Think of it as a form with labelled boxes.

1

Agent

Says which machine runs the pipeline by default. It can also be set to “none” at the top so that each stage chooses its own machine.

2

Options

Global switches, such as an overall time limit or how many old builds to keep.

3

Environment

Named values, such as the application name or a secret reference, that the stages can use.

4

Stages

The required heart of the pipeline. It holds the list of individual stages, in the order they should run.

5

Post

Actions that run when the whole pipeline ends, such as sending a message or cleaning up.

Inside the stages part, every individual stage has a name and its own inner contents. Inside each stage there must be a steps part, which lists the real actions. A stage may also carry its own optional settings, such as which agent to use, which conditions must be true, and which actions to run after that stage only.

PartRequired?What it does
StagesYesHolds the list of stages for the pipeline.
StageYes, at least oneA named group of steps.
StepsYes, inside each stageThe real actions that do the work.
AgentYes, at top level or per stageChooses the machine that runs the work.
PostNoActions that run after a stage or after the whole pipeline.
When, options, environment, inputNoOptional controls for one stage.

6How Jenkins Runs a Stage Internally

Let us follow one pipeline from the doorbell ringing to the final report, paying attention to what happens around each stage.

1

The pipeline starts

A trigger fires, and the controller loads the Jenkinsfile. It checks that the structure is valid before doing any real work. A mistake in the layout is caught right away.

2

The first stage begins

Jenkins finds a free executor on a matching agent. If none is free, the stage waits in the queue like a customer at a bakery counter.

3

Conditions are checked

If the stage has a condition, Jenkins tests it. If the condition is false, the stage is skipped and shown as skipped on the screen.

4

Steps run in order

The agent performs each step from top to bottom. Every line of output is streamed back so you can watch progress live.

5

The stage ends with a result

If every step worked, the stage is marked successful. If a step failed, the stage is marked failed. The time taken is recorded.

6

Stage post actions run

If the stage has its own after-actions, they run now, depending on the stage result.

7

The next stage starts, or the pipeline stops

After a successful stage, Jenkins moves on. After a failed stage, the remaining stages are normally skipped, and the pipeline-level post actions run.

sequenceDiagram
  participant C as Jenkins Controller
  participant Q as Build Queue
  participant A as Build Agent
  participant V as Stage View
  C->>C: Load and validate Jenkinsfile
  C->>Q: Request executor for Stage 1
  Q->>A: Assign free executor
  C->>C: Check stage condition
  A->>A: Run steps in order
  A-->>C: Send logs and result
  C->>V: Update stage box and timing
  C->>Q: Request executor for Stage 2
  Note over C,A: Repeat until all stages finish or one fails
Figure 2: The controller coordinates each stage while the agent performs the steps.

A clever trick: saved progress

Pipelines can run for hours, and computers sometimes restart. Jenkins saves the state of a running pipeline to disk as it goes, stage by stage. After a controller restart, the pipeline can usually continue from where it stopped instead of starting over. Think of saving your game at each checkpoint.

The automatic first stage

If your pipeline downloads code from a repository automatically, you may notice an extra stage on the screen with a name that starts with the word “Declarative”, such as the checkout of source code. Jenkins adds it for you. It is a helper stage, not one you wrote. Another helper appears at the end when the pipeline has post actions. Do not be surprised by these guests.

7Data Flow Between Stages

Stages often need to hand things to each other, such as a finished program package. How does that work?

When two stages run on the same agent, they share the same workspace folder. A file created in the Build stage is simply still there when the Test stage starts. This is the easiest situation.

When two stages run on different agents, the second agent has its own empty workspace. The files from the first agent are not there. Jenkins offers a tool for this called stash and unstash. Stash means “put these files in a temporary box on the controller”. Unstash means “take the files out of that box on another agent”. It works well for small or medium files. For big files, teams store the results in an artifact repository, a warehouse for finished packages, and let later stages download them from there.

flowchart LR
  B["Build Stage on Agent 1"] -->|"stash files"| BOX[("Temporary Box on Controller")]
  BOX -->|"unstash files"| T["Test Stage on Agent 2"]
  B -->|"upload package"| REPO[("Artifact Repository")]
  REPO -->|"download package"| D["Deploy Stage on Agent 3"]
Figure 3: Two ways to pass files between stages that run on different machines.
Everyday analogy

Picture a relay race. The runner in the first leg must hand the baton to the runner in the second leg. If they run on the same track, the handover is easy. If they are in different cities, you must post the baton in a parcel box and let the next runner collect it. Stash and unstash are that parcel box.

!
Warning

Do not stash very large files. It puts heavy load on the controller. Use an artifact repository for anything big.

8Choosing Where a Stage Runs

Every stage needs a machine. You can pick one for the whole pipeline or a different one for each stage.

The agent setting decides which machine runs the work. If you set it at the very top of the pipeline, every stage uses it. If you instead set the top-level agent to “none” and give each stage its own agent, every stage chooses the machine that suits it best.

Agents can be described in several ways. You can ask for any free agent, or an agent that carries a certain label such as “linux” or “windows”, or a fresh temporary container created just for that stage. A container is a small, sealed box that holds a program and everything it needs, and it disappears when the stage ends. This gives every stage a clean room with the exact tools it requires.

One agent for all stages

  • Simple to understand
  • Files are shared automatically in one workspace
  • Fewer machine start-ups, so it can be faster

A different agent per stage

  • Each stage gets exactly the tools it needs
  • Heavy stages can use big machines and light stages small ones
  • Files must be passed with stash or an artifact repository
*
Tip

A stage that waits for a human, such as an approval, should not hold a worker machine while it waits. Set the agent to none for that stage so no executor is wasted.

9Controlling a Stage: Conditions, Time Limits, and More

A stage can carry extra settings that decide whether it runs, how long it may take, and what it needs.

Condition

When

Runs the stage only if a condition is true. For example, deploy only when the branch is the main branch, or only when a certain tag is present.

Limit

Timeout

Stops the stage if it takes longer than a set time. This prevents a stuck stage from holding a worker forever.

Retry

Retry

Tries the stage again a few times if it fails. Useful for flaky network steps, dangerous if it hides real problems.

Values

Environment

Gives the stage named values, such as the target server name, or safe access to a stored secret.

Human

Input

Pauses the stage and asks a person to approve or provide answers before it continues.

Tidy

Post

Runs cleanup or notification actions after this stage, depending on its result.

The “when” condition in more detail

The when setting is one of the most useful stage controls. It lets one Jenkinsfile handle many situations. A stage that publishes a release can carry a condition that says “only on the main branch”, so ordinary feature branches skip it. When a condition is false, the stage is drawn as skipped and no steps run.

Conditions can check the branch name, whether the build was started by a tag, the value of an environment name, whether certain files changed, or even a small custom test. They can also be combined with “all of”, “any of”, and “not” for finer control. By default, Jenkins checks the condition before it starts the stage’s agent and before it asks for approval, which avoids wasting machines on stages that will be skipped.

Everyday analogy

Think of a traffic light before a road junction. The road is always there, but the light decides whether cars may pass right now. The when condition is a traffic light in front of the stage.

Manual approval stages

Many teams place an approval gate before the final deployment. A stage with an input setting pauses and shows a button on the screen. A permitted person can approve or abort. This keeps humans in charge of risky moves such as sending a change to real users, while everything before it stays automatic.

!
Warning

Always give approval stages a time limit. Otherwise a forgotten approval can leave a pipeline waiting for days.

10Parallel Stages: Doing Work Side by Side

Normally stages run one after another. But some work does not depend on each other, and can happen at the same time.

Imagine you must test your program on three different systems. Running the three checks one by one would take three times as long. If you have enough machines, you can run them in parallel, meaning at the same moment. Jenkins lets you place several stages inside a parallel block. They start together, and the pipeline moves on only when all of them finish.

flowchart LR
  B["Build"] --> P{"Parallel Tests"}
  P --> T1["Test on Linux"]
  P --> T2["Test on Windows"]
  P --> T3["Test on Mac"]
  T1 --> J["Join Results"]
  T2 --> J
  T3 --> J
  J --> D["Deploy"]
Figure 4: Three test stages run at the same time, then the pipeline continues once all are done.

Fail fast

By default, if one parallel stage fails, the others keep running until they finish. If you would rather stop everything immediately, there is a fail fast option. When any parallel branch fails, the rest are aborted at once. This saves time and machines when a single failure already means the whole result is bad.

Sequential stages and nesting

Stages can also be placed inside other stages. A stage can hold a group of smaller stages that run in order, and a parallel group can contain such groups. This lets you build layouts like “in parallel, do Linux work and Windows work, where each of those has its own Build and Test in sequence”. Use nesting carefully, because deep nesting quickly becomes hard to read.

Matrix: many combinations from one recipe

The matrix feature lets you describe a set of axes, such as operating system and version, and Jenkins creates a parallel stage for every combination. It is like a multiplication table: three systems times two versions gives six stages, all from one short description. This avoids copying the same stage again and again.

LayoutHow stages runBest used for
SequentialOne after anotherSteps that depend on each other, such as Build then Test
ParallelAt the same timeIndependent checks, such as tests on different systems
NestedGroups inside groupsComplex flows that mix order and side-by-side work
MatrixMany combinations automaticallyTesting across many platforms and versions
i
Good to know

Running things in parallel needs enough free executors. If there are not enough, some parallel stages simply wait in the queue, and you gain less speed than expected.

11Stage Results and Post Actions

Every stage ends with a result, and you can decide what happens for each kind of result.

After a stage finishes, it has one of a few results. Success means all steps worked. Failure means a step broke. Unstable means the work finished but something like a test failed. Aborted means a person or a time limit stopped it. Skipped means a condition said the stage should not run.

The post section lets you attach actions that run depending on these results. Common choices include the following.

Always

always

Runs no matter what happened. Ideal for cleanup, like deleting temporary files.

Good

success

Runs only when everything worked. Good for celebratory messages or saving results.

Bad

failure

Runs only when something failed. Perfect for sending a “please look at this” alert.

Change

changed and fixed

Runs when the result differs from the previous run, or when a broken pipeline becomes healthy again.

Doubt

unstable and aborted

Runs when tests failed but the run finished, or when the run was stopped early.

Last

cleanup

Runs at the very end, after all the other post conditions, even in unusual situations. It is the final sweeper.

You can place post actions in two places: inside a single stage, so they run right after that stage, or at the pipeline level, so they run when the whole pipeline ends. Cleanup and notifications usually belong at the pipeline level, while stage-level post actions suit things like publishing that stage’s own test reports.

*
Tip

Publish test reports in the post section using the “always” condition. That way you can still read the report of a failed test run, which is exactly when you need it most.

12Seeing Stages on the Screen

One of the greatest gifts of stages is visibility. Jenkins draws them for you.

Jenkins can show a grid on the job page called the Stage View. Each column is a stage. Each row is one run of the pipeline. Boxes are coloured by result, and each shows how long that stage took. At a glance you can see that the Build stage takes two minutes, the Test stage takes twelve minutes, and that the last three runs failed at Deploy.

Newer views can show the pipeline as a graph, including parallel branches drawn side by side and a detailed log for each stage. Clicking on a failed stage takes you straight to its own log, so you do not have to search through the whole build output. This is where stages truly pay off: they shorten the time between “something is red” and “I know where to look”.

Everyday analogy

A hospital patient chart lists temperature, pulse, and blood pressure in separate columns over time. A doctor spots trouble instantly. The Stage View is a patient chart for your pipeline, with one column per stage.

Restarting from a stage

For declarative pipelines, Jenkins allows you to restart a finished run from a chosen stage. If the Deploy stage failed because of a temporary network problem, you can restart from Deploy and skip the long Build and Test stages that already passed. This saves time and is only possible because the work is divided into named stages. Note that a restart begins with the same code and settings as the original run.

Naming stages well

Because stage names appear on screens, in messages, and in reports, good naming matters. Keep names short, clear, and consistent across projects. If every team calls its test phase “Unit Tests”, people can compare pipelines easily. Avoid putting changing details such as dates or numbers in stage names, because that makes history harder to compare.

13Common Stages in a Real Pipeline

While every project is different, most delivery pipelines contain a familiar set of stages.

Checkout

Downloads the latest code from the repository into the workspace. Every later stage depends on this one.

Build

Turns the raw code into a working program, a step often called compiling and packaging. If this fails, there is no point testing.

Unit Tests

Runs small, fast automated checks on individual pieces of the program. These should finish in minutes and run early, because quick feedback is precious.

Code Quality and Security Scan

Checks the code for style problems and known weaknesses, and checks the libraries it uses for known security holes.

Integration Tests

Checks that different parts of the system work together, often by starting a temporary copy of the application and its database.

Package and Publish

Creates the final deliverable, such as a container image, and uploads it to an artifact repository.

Deploy to Staging

Installs the package in a practice environment that looks like the real one, for final checks.

Approval

A human gate that asks a responsible person to allow the release to go on.

Deploy to Production

Delivers the tested package to real users, often gradually to limit risk.

flowchart LR
  C["Checkout"] --> B["Build"]
  B --> U["Unit Tests"]
  U --> Q["Quality and Security Scan"]
  Q --> I["Integration Tests"]
  I --> P["Package and Publish"]
  P --> S["Deploy to Staging"]
  S --> A{"Approval"}
  A -->|"approved"| R["Deploy to Production"]
  A -->|"rejected"| X["Stop and Notify"]
  U -->|"tests fail"| F["Fail and Alert Team"]
Figure 5: A common set of stages. A failure early on stops the line before anything reaches users.

Notice how the cheap, fast checks come first and the expensive, risky ones come last. This idea is called fail fast in pipeline design: if something is going to break, let it break as early and as cheaply as possible.

14Advantages, Disadvantages, and Trade-offs

Stages bring great benefits, but every design choice has a price. Knowing both sides helps you decide how many stages to use and how to shape them.

Advantages

  • Clear structure that anyone can read at a glance
  • Failures point straight to the phase that broke
  • Timing per stage reveals slow parts
  • Different stages can use different machines
  • Conditions let one file handle many situations
  • Declarative pipelines can restart from a failed stage
  • Parallel stages shorten total time

Disadvantages

  • Too many tiny stages make screens cluttered and add overhead
  • Switching agents between stages costs start-up time
  • Passing files between machines adds extra work
  • Deeply nested layouts become hard to read
  • Parallel work needs enough machines to help

How many stages is right?

There is no magic number, but there is a helpful guide. Make a stage when the work has its own clear goal, its own possible failure, and something worth timing or controlling separately. Do not make a stage for every single command. A pipeline with forty tiny stages is as unreadable as one with none. A pipeline of about four to ten well-named stages is often a comfortable size.

ChoiceFewer, larger stagesMore, smaller stages
ReadabilitySimple, but a failure covers a lot of groundPrecise, but the screen can get crowded
DebuggingYou may search a long logYou jump straight to the failing piece
SpeedLess overheadMore overhead, more chances to run in parallel
RestartsRedo a lot of workRedo only what failed

15Security Around Stages

Stages often touch secrets and live servers, so they deserve careful protection.

Keep secrets out of the file

Some stages need passwords, keys, or tokens, for example to publish a package or reach a server. Never type these into the Jenkinsfile. Jenkins has a credentials store that keeps secrets encrypted. A stage refers to a secret by a friendly name, and Jenkins hands the real value to the stage only while it runs, hiding it in the log output. Give the secret to the smallest possible piece of work, ideally only the one stage that truly needs it.

Protect the risky stages

The stage that deploys to production is the most valuable target. Combine several protections: run it only on trusted branches using a when condition, require a human approval, allow only a small group of people to approve, and run it on a dedicated agent that other jobs cannot use.

Do not trust unknown code

If your pipeline builds code from public pull requests, an outsider might try to change the Jenkinsfile to steal secrets. Good setups build such untrusted changes on throwaway agents with no access to secrets, and only run the sensitive stages for code that has been reviewed and merged.

Other helpful habits

  • Least privilege. Give each stage only the access it needs.
  • Keep the controller free of builds. Stages should run on agents, not on the brain of the system.
  • Use the script sandbox. Pipeline scripts run in a restricted mode, and unusual actions need an administrator’s approval.
  • Update regularly. Keep Jenkins and its plugins current to close known holes.
!
Warning

Anyone who can change the Jenkinsfile can change what your stages do. Treat pipeline files with the same care as application code, with reviews before changes go live.

16Monitoring, Logging, and Metrics for Stages

Because stages are named and timed, they are perfect for measuring how healthy your delivery process is.

Speed

Stage duration

How long each stage takes. A stage that slowly grows longer each week may signal too many tests or a slow download.

Quality

Failure rate per stage

Which stage fails most often? That is the best place to invest effort in fixing flaky tests or unreliable steps.

Wait

Queue time

How long a stage waits for a free executor. Long waits mean you need more agents or better labels.

Flow

Total pipeline time

The time from code push to finished delivery. This is the number developers feel every day.

Each stage has its own log section, so when something fails you read only the relevant part. Many teams also send stage timings and results to monitoring tools such as Prometheus and show them on Grafana dashboards. Build logs can be sent to a central search system so that engineers can look across thousands of runs. Like nurses watching a patient’s pulse and temperature, they can spot small changes before they turn into emergencies.

*
Tip

Once a month, look at the slowest stage in your busiest pipeline. Shortening that single stage often gives the biggest speed-up for the whole team.

17Design Patterns and Anti-Patterns

A pattern is a proven habit. An anti-pattern is a tempting shortcut that usually causes pain later.

Patterns that work

Build once, deploy many

Create one package in the Build stage, then promote that exact same package through Staging and Production. You test exactly what you ship.

Fail fast

Put the cheapest, quickest checks first. If a ten-second check fails, there is no reason to wait forty minutes for the big tests.

One purpose per stage

Each stage should have a single clear goal. That makes names meaningful and failures easy to understand.

Parallelize the independent

Run checks that do not depend on each other side by side, such as tests on different platforms, to cut total time.

Approval gates before risk

Place a human approval right before the riskiest stage, and keep everything before it automatic.

Shared library stages

Write common stage logic once in a shared library, so fifty projects reuse the same trusted Deploy stage and fixes reach everyone together.

Anti-patterns to avoid

ANTI-PATTERN 01Avoid
The pattern

Putting the entire pipeline into one giant stage called “Everything”, with dozens of steps inside.

Why it hurts

The screen shows one big box. A failure gives no clue where to look, timing is meaningless, and a restart redoes all the work.

The better way

Split the work into clear stages such as Build, Test, Package, and Deploy, each with a single goal.

ANTI-PATTERN 02Avoid
The pattern

Making a stage for every tiny command, resulting in thirty or forty boxes on the screen.

Why it hurts

The view becomes cluttered and hard to read, and small overheads add up.

The better way

Group related commands into one stage with a meaningful name, and keep the total to a comfortable number.

ANTI-PATTERN 03Avoid
The pattern

Holding a worker machine while a stage waits for a human approval.

Why it hurts

The executor sits idle for hours or days, blocking other builds and wasting money.

The better way

Set the agent to none for the approval stage and add a time limit, so no machine is tied up and forgotten approvals expire.

ANTI-PATTERN 04Avoid
The pattern

Rebuilding the program separately in the Test and Deploy stages.

Why it hurts

Each rebuild may differ slightly, so what you tested may not be what you shipped.

The better way

Build once, save the package, and let later stages use that same package.

18Best Practices and Common Mistakes

These habits separate a calm pipeline from a chaotic one.

Best practices

  1. Give every stage a clear, consistent name that says what it does, such as Build, Unit Tests, or Deploy to Staging.
  2. Give every stage one clear goal. If you cannot describe it in one short sentence, it may be two stages.
  3. Order stages from cheap and fast to expensive and risky, so failures appear as early as possible.
  4. Use time limits. A timeout on stages, especially those that wait or call outside systems, keeps stuck runs from hanging.
  5. Use when conditions to skip stages that do not apply, such as publishing on feature branches.
  6. Pick the agent per stage carefully, and use labels or containers so each stage gets the tools it needs.
  7. Run independent stages in parallel, but make sure you have enough executors.
  8. Clean up in post actions using the always condition, so temporary files never pile up.
  9. Publish reports even on failure, because a failed run is when you need them most.
  10. Keep secrets in the credentials store, and expose them only to the stage that needs them.
  11. Keep the Jenkinsfile in the repository and review changes like any other code.
  12. Reuse stage logic through shared libraries when many projects need the same thing.

Common mistakes

Mistake

Vague names

Names like Stage 1 or Misc tell nobody anything. Rename them to describe the goal.

Mistake

No time limits

A stuck stage can hold a machine for hours. Always set a sensible limit.

Mistake

Blind retries

Retrying a failing stage again and again can hide a real bug. Retry only genuinely flaky steps, and only a few times.

Mistake

Forgetting shared files

Assuming files from an earlier stage exist on a different agent. Use stash or an artifact repository.

Mistake

Ignoring flaky tests

Tests that fail randomly teach people to shrug at red stages. Repair or remove them.

Mistake

Secrets everywhere

Exposing a secret to the entire pipeline when only one stage needs it increases the risk.

*
Tip

Test the readability of your pipeline with a simple question: “Could a new teammate look at the stage boxes and explain what happens?” If yes, your stages are doing their job.

19Real-World Usage

Stages appear in almost every real Jenkins pipeline. Here are common ways teams use them.

The pull request checker

Every time someone proposes a code change, a pipeline runs Checkout, Build, and Unit Tests. Reviewers see a green or red mark next to the proposal before they approve it, and a red mark points to the exact stage that failed.

Cross-platform testing

A team that ships software for Windows, Linux, and Mac uses parallel stages, or a matrix, to test on all three at the same time. What used to take an hour is done in twenty minutes.

The release train

A pipeline builds once, deploys to Staging, waits for a human approval stage, and then deploys to Production. Operations staff approve a release with a single click, without knowing the details behind it.

Mobile app builds

Stages labelled for Mac agents build iPhone apps, while stages labelled for Linux agents build Android apps, all coordinated in one pipeline.

Large engineering organizations

Companies running Jenkins at large scale, with many teams and thousands of pipelines, commonly rely on shared libraries so that standard stages such as Build, Scan, and Deploy are written once and reused everywhere. This keeps pipelines consistent and makes security fixes reach every project together. Internet-scale companies such as Netflix have publicly described using Jenkins as part of their delivery flow alongside other tools.

Security-conscious delivery

Regulated teams, such as banks, add scan stages for code weaknesses and vulnerable libraries, and approval stages with recorded names, so auditors can see who allowed each release.

A typical growth story

A small team begins with one long list of commands in a single job. After a painful outage they cannot find the failing part, so they split the work into Build, Test, and Deploy stages. Next they add a quality scan and run tests in parallel to save time. Later they add an approval stage before Production and a time limit on every stage. Finally they move the common stages into a shared library so new projects start with a good pipeline from day one. At each step the change was small, and the team never had to start over.

20Frequently Asked Questions

Q1What is a stage in Jenkins?
A stage is a named group of steps inside a pipeline, such as Build, Test, or Deploy. It gives the pipeline structure, makes progress visible on the screen, and lets you control and time one phase separately from the others.
Q2What is the difference between a stage and a step?
A step is one small action, like running a command. A stage is a named group of steps that together achieve one goal. Steps do the work, and stages organize it.
Q3What is the difference between a stage and a pipeline?
The pipeline is the whole assembly line. Stages are the named phases inside it. A pipeline contains one or more stages.
Q4Can a pipeline have only one stage?
Yes, a declarative pipeline needs at least one stage. But a single stage gives few of the benefits, so most useful pipelines have several.
Q5Do stages run in order or at the same time?
By default they run one after another in the order written. You can place stages inside a parallel block, or use a matrix, so that they run at the same time.
Q6What happens if a stage fails?
Normally the failed stage is marked failed, the remaining stages are skipped, and the post actions run. In a parallel group, other branches keep going unless you turn on the fail fast option.
Q7Can each stage use a different machine?
Yes. You can set the agent for the whole pipeline or separately for each stage, using labels or fresh containers. If stages use different machines, you must pass files between them with stash or an artifact repository.
Q8How do I run a stage only sometimes?
Use the when condition. For example, you can run a deployment stage only on the main branch. When the condition is false, the stage is skipped and shown as skipped.
Q9How do I ask a person to approve before a stage continues?
Use the input setting on a stage. The pipeline pauses and shows an approval button. Add a time limit, and set the agent to none for that stage so no worker machine is wasted while waiting.
Q10Can I restart a pipeline from a failed stage?
For declarative pipelines, yes. Jenkins can restart a finished run from a chosen stage, skipping the earlier ones. This saves time when a late stage fails for a temporary reason.
Q11What is the extra stage that begins with the word Declarative?
Jenkins adds helper stages automatically, such as one for checking out the source code and one for the post actions at the end. They are not stages you wrote, and they are normal.
Q12How many stages should a pipeline have?
There is no fixed number. Make a stage when work has its own goal and a possible separate failure. Four to ten well-named stages is often comfortable. Avoid one giant stage and avoid dozens of tiny ones.
Q13Do stages work in scripted pipelines too?
Yes, but there a stage is simply a named block used mainly for labelling and display. Declarative pipelines make stages a required, checked part of the structure, which is why most teams begin with the declarative style.

21Summary and Key Takeaways

You started in a bicycle factory and finished with a complete picture of how Jenkins organizes automated work into clear, named phases.

Key Takeaways

  • A stage is a named group of steps inside a pipeline. It turns a shapeless list of chores into clear phases such as Build, Test, and Deploy.
  • Stages make pipelines visible, measurable, and fixable. Jenkins draws each stage, times it, and lets you jump to its own log when something fails.
  • Stages run in order by default, and can run side by side with parallel blocks or a matrix, so independent work finishes sooner.
  • Each stage can choose its own agent, conditions, time limit, and post actions. This gives fine control without touching the rest of the pipeline.
  • Files must be passed on purpose when stages use different machines, using stash and unstash for small files or an artifact repository for large ones.
  • Design stages well: one clear goal each, cheap and fast checks first, human approvals before risky moves, and time limits everywhere.
  • Protect the sensitive stages. Keep secrets in the credentials store, expose them only where needed, and review changes to the Jenkinsfile like any other code.