Skip to main content
In this guide, we’ll explore how to leverage the newContainerPerStage() option to control container lifecycle in a Jenkins Declarative Pipeline. By default, a top-level dockerfile agent builds one container and reuses it across all stages. With newContainerPerStage(), each stage runs in its own fresh container—ensuring clean, isolated environments.

Pipeline Strategies Overview


1. Pipeline with Stage-Specific Agents

Assigning agents at the stage level offers maximum flexibility but can become verbose:

2. Single Global Dockerfile Agent

Simplify the pipeline by declaring one global Dockerfile agent. All stages execute in the same container built from Dockerfile.cowsay:
Jenkins will:
  1. Build the Docker image:
  2. Launch a single container.
  3. Run each sh step inside that container.
  4. Tear down the container after pipeline completion.

3. Sharing State Across Stages

Because the container and workspace persist, you can create files in one stage and consume them later:
With a single container, workspace contents persist across stages—ideal for sharing build artifacts or test reports.

4. Isolating Stages with newContainerPerStage()

To enforce a clean container per stage (and thus no shared workspace), enable the newContainerPerStage() pipeline option:
With newContainerPerStage(), each stage builds its own image and launches a separate container. Files created in one stage will not be available in subsequent stages.
The image shows a webpage from the Jenkins documentation, specifically focusing on pipeline syntax options. It includes a highlighted section about the "newContainerPerStage" option.
For detailed syntax, refer to the Jenkins Pipeline options section.

Watch Video

Practice Lab