In the previous lesson, orders-api gained traceability with build-info.txt and a real smoke check, but all its stages still run one after the other, even though some of them do not depend on each other. Every minute a pipeline takes to respond is a minute Diego spends waiting before he knows whether his change is correct. In this lesson you will learn to run work in parallel inside a declarative pipeline with parallel, to decide what can be parallelized without two processes stepping on each other in the same workspace, to cut the branches short as soon as one fails with failFast, and to use the matrix directive to repeat the same stages with different combinations of values. To practice it you will meet TecnoShop's second project, catalog-web, a Node.js frontend that must work on three Node versions.
Why Parallelize: Feedback Time
Feedback time is what elapses from the moment someone pushes a change until they know whether it works. If it is long, people stop waiting, pile up unverified changes and failures accumulate. Laura measures the typical times for orders-api (they may vary on your machine):
| Stage | Typical duration |
|---|---|
| Build | 25 s |
| Tests | 45 s |
| Dependency analysis (new) | 15 s |
| Package | 15 s |
| Smoke | 20 s |
In sequence, the five add up to 2 minutes. But Tests and Dependency analysis do not depend on each other: both only need the compiled code. If they run at the same time, the block takes as long as the slower one (45 s) and the build drops to about 1 min 45 s. In large projects, with test suites lasting several minutes, the gain is much bigger.
flowchart LR
C["Build"] --> V{"Checks<br/>(in parallel)"}
V --> P["Tests"]
V --> A["Dependency<br/>analysis"]
P --> E["Package"]
A --> E
E --> H["Smoke"]
H --> D["Deploy to dev"]
The rule for deciding what to parallelize: independent tasks, which do not need each other and do not write to the same files.
parallel in a Declarative Pipeline
stage('Checks') {
parallel {
stage('Branch A') {
steps {
echo 'Runs at the same time as branch B'
}
}
stage('Branch B') {
steps {
echo 'Runs at the same time as branch A'
}
}
}
}stage('Checks') { parallel { ... } }: a container stage whose children run simultaneously. As you saw in 04-01, a stage contains only one ofsteps,stages,parallelormatrix.- Each child is a complete
stage: it can have its ownwhen,options,environment,postand evenagent. - A parallel branch can in turn contain
stagesto run several stages in sequence within the branch. What is not allowed is nesting oneparallelinside another. - The
Checksstage finishes when all its branches finish. Its result is the worst of them.
In the console, the lines from each branch appear interleaved and prefixed with the branch name, for example [Branch A] Runs at the same time as branch B. That is why it is much more convenient to use Pipeline Graph View to read the log of a specific branch, as you will see at the end.
The Shared Workspace Problem
When parallel branches do not declare their own agent, they run on the same node and in the same workspace as the rest of the pipeline. This is convenient (they see the compiled code), but dangerous: if two branches write to the same files at the same time, the result is unpredictable.
With Maven the risk is very specific: almost all its goals write to target/. Imagine these two branches:
| Branch | Command | Writes to target/? |
|---|---|---|
| Tests | ./mvnw -B test |
Yes: target/classes, target/test-classes, target/surefire-reports |
| Analysis (bad option) | ./mvnw -B dependency:analyze |
Yes: before analyzing, it runs the phases up to test-compile on its own, and they compile into target/ |
| Analysis (good option) | ./mvnw -B dependency:tree -DoutputFile=dependencies.txt |
No: it only resolves dependencies and writes dependencies.txt at the root |
With dependency:analyze, two Maven processes would compile into target/classes at the same time: one may delete or overwrite classes the other is reading. The result is intermittent failures such as ClassNotFoundException or ZipException, which show up in one build out of ten and are very hard to diagnose. That is why the good option is to choose tasks that do not write to the same place.
Strategies for avoiding the problem:
| Strategy | How | When |
|---|---|---|
| Choose tasks that do not collide | One branch writes to target/; the other does not write, or writes elsewhere |
The one we use today in orders-api |
| Separate the working directory | Each branch works in its own subdirectory (dir('branch-x')) with its own copy of what it needs |
Tasks that generate their own files |
| Separate workspaces | Each branch declares its own agent and gets its own workspace (and its own checkout) |
The natural choice once there are agents: 05-01 |
Two more details:
- The local
~/.m2repository is shared by all builds on the node, but it is not the problem here: afterBuild, the dependencies are already downloaded and both branches only read them. The real conflict is intarget/. - The Maven Wrapper downloads Maven the first time. Because
Buildruns before the parallel block, Maven is already downloaded when the branches start, so there are no two simultaneous downloads.
Applying It in orders-api: the Checks Stage
stage('Checks') {
failFast true
parallel {
stage('Tests') {
when {
expression { params.RUN_TESTS }
}
options {
timeout(time: 10, unit: 'MINUTES')
}
steps {
sh './mvnw -B test'
}
post {
failure {
echo 'The tests failed: check the log of this stage (reports in target/surefire-reports).'
}
}
}
stage('Dependency analysis') {
options {
timeout(time: 5, unit: 'MINUTES')
}
steps {
sh label: 'Dependency tree', script: './mvnw -B dependency:tree -DoutputFile=dependencies.txt'
archiveArtifacts artifacts: 'dependencies.txt'
}
}
}
}- The familiar
Testsstage becomes a branch ofChecks, with itswhen, itstimeoutand itspostintact. IfRUN_TESTSis unchecked, the branch is skipped and the other one runs anyway. Dependency analysis:dependency:treegenerates the full dependency tree (direct and transitive) independencies.txt, which is archived. Marta will use it to review which library versions each build includes; in DevSecOps you will see real vulnerability analysis.failFast true: explained below.
The contents of dependencies.txt look like this:
com.tecnoshop:orders-api:jar:1.0.0-SNAPSHOT +- org.springframework.boot:spring-boot-starter-web:jar:3.5.7:compile | +- org.springframework.boot:spring-boot-starter:jar:3.5.7:compile ... \- org.springframework.boot:spring-boot-starter-test:jar:3.5.7:test
failFast and parallelsAlwaysFailFast()
By default, if one branch fails, the others keep running until the end. Sometimes that is what you want (seeing all the problems at once), but it is often a waste of time and executors: if the tests failed, the build is not going to be deployed anyway.
| Option | Where | Effect |
|---|---|---|
failFast true |
Inside a stage with parallel or matrix |
If one branch fails, the others in that stage are aborted |
parallelsAlwaysFailFast() |
In the pipeline's options |
Applies failFast true to all parallel stages and matrices |
With failFast true, if Tests fails while the analysis is still running, the analysis is aborted and shows up in the view as aborted (gray), not as failed. In orders-api that is what we want: nobody cares about a dependency analysis of code that does not pass its tests.
Executors and Resource Contention
Parallelizing is not free. It helps to distinguish two cases:
| Case | How many executors does it use? | Workspace |
|---|---|---|
Branches without their own agent |
No extra ones: they share the pipeline's executor | The same one |
Branches with their own agent |
One per branch, while it runs | One per branch |
The built-in node in your environment has 2 executors. That means:
- The
Checksbranches do not use extra executors, but they do use CPU, memory and disk in thejenkins-controllercontainer: two Maven JVMs at once. If your machine is short on resources, you will notice that each branch takes longer than in sequence, and the time saved will be smaller than expected. - If a pipeline with a global
agent anystarts branches with their ownagent any, the pipeline is already using one of the two executors, so only one is left for the branches: they will run one at a time. With a globalagent none, the two branches can use both executors. - Branches that request more executors than are available wait in the queue. You will see this shortly with the
catalog-webmatrix: three cells and two executors.
The rule of thumb: parallelize what is independent and fits within your resources. Adding executors and spreading the work across agents is the job of Managing Jenkins Nodes and Agents and Scaling Jenkins.
The Second Project: catalog-web
TecnoShop has a second team that maintains the web catalog: the frontend that displays the products and their prices. Its code is built with Node.js and npm, and it must work on three Node versions, because not all of its environments have been upgraded at the same time. In the text we will call it tecnoshop/catalog-web; you will create it in your account as <your-username>/catalog-web, just as you did with orders-api in 01-04.
Repository structure:
catalog-web/
├── .gitignore
├── package.json
├── package-lock.json (generated by npm install)
├── scripts/
│ └── build.js
└── src/
├── prices.js
└── prices.test.jspackage.json
{
"name": "catalog-web",
"version": "1.0.0",
"private": true,
"description": "TecnoShop web catalog (practice project for the Jenkins course)",
"main": "src/prices.js",
"scripts": {
"test": "jest --ci",
"build": "node scripts/build.js"
},
"engines": {
"node": ">=18"
},
"devDependencies": {
"jest": "^29.7.0"
}
}scripts.test:npm testruns Jest, the testing framework.--ciadjusts its behavior to a continuous integration environment (for example, it does not create new snapshots without permission).scripts.build:npm run buildruns our build script.engines.node: documents the minimum supported Node version.devDependencies: Jest is only needed for development and testing, not in production.
src/prices.js
'use strict';
function validateAmount(amount) {
if (typeof amount !== 'number' || !Number.isFinite(amount) || amount < 0) {
throw new TypeError(`Invalid amount: ${amount}`);
}
}
function formatPrice(amount) {
validateAmount(amount);
return `${amount.toFixed(2).replace('.', ',')} €`;
}
function applyDiscount(amount, percentage) {
validateAmount(amount);
if (typeof percentage !== 'number' || percentage < 0 || percentage > 100) {
throw new RangeError(`Invalid percentage: ${percentage}`);
}
return Math.round(amount * (100 - percentage)) / 100;
}
function finalPrice(amount, percentage) {
return formatPrice(applyDiscount(amount, percentage));
}
module.exports = { formatPrice, applyDiscount, finalPrice };validateAmount: rejects anything that is not a finite, non-negative number.Number.isFiniterules outNaNandInfinity.formatPrice:toFixed(2)keeps two decimal places (59.9→"59.90") andreplace('.', ',')switches to the decimal comma used in Spain, where TecnoShop sells:"59,90 €".applyDiscount: calculates the discounted amount rounded to the cent. Multiplying by(100 - percentage), rounding and dividing by 100 avoids carrying floating-point errors along.module.exports: exports the functions so other modules and the tests can use them (CommonJS format, compatible with all three Node versions).
src/prices.test.js
const { formatPrice, applyDiscount, finalPrice } = require('./prices');
describe('formatPrice', () => {
test('uses a decimal comma and the euro sign', () => {
expect(formatPrice(59.9)).toBe('59,90 €');
});
test('formats zero', () => {
expect(formatPrice(0)).toBe('0,00 €');
});
test('rejects negative amounts', () => {
expect(() => formatPrice(-1)).toThrow(TypeError);
});
});
describe('applyDiscount', () => {
test('applies a 15% discount', () => {
expect(applyDiscount(100, 15)).toBe(85);
});
test('rounds to the cent', () => {
expect(applyDiscount(59.9, 10)).toBe(53.91);
});
test('rejects percentages outside 0-100', () => {
expect(() => applyDiscount(10, 120)).toThrow(RangeError);
});
});
describe('finalPrice', () => {
test('combines discount and formatting', () => {
expect(finalPrice(124.5, 25)).toBe('93,38 €');
});
});describe: groups related tests.test: one specific test.expect(value).toBe(expected): checks strict equality.expect(() => ...).toThrow(TypeError): checks that the function throws that type of error. Notice the arrow function: if you calledformatPrice(-1)directly, the error would be thrown before Jest could catch it.
scripts/build.js
'use strict';
const fs = require('fs');
const path = require('path');
const srcDir = path.join(__dirname, '..', 'src');
const distDir = path.join(__dirname, '..', 'dist');
fs.rmSync(distDir, { recursive: true, force: true });
fs.mkdirSync(distDir, { recursive: true });
const files = fs.readdirSync(srcDir)
.filter((f) => f.endsWith('.js') && !f.endsWith('.test.js'));
for (const file of files) {
fs.copyFileSync(path.join(srcDir, file), path.join(distDir, file));
}
const info = {
application: 'catalog-web',
version: require('../package.json').version,
node: process.version
};
fs.writeFileSync(path.join(distDir, 'build.json'), JSON.stringify(info, null, 2) + '\n');
console.log(`Build completed: ${files.length} file(s) in dist/ with Node ${process.version}`);- It deletes and recreates
dist/, copies the.jsfiles fromsrc/except the tests and writesdist/build.jsonwith the application version and the Node version used. In a real project, a bundler such as Vite or webpack would do this job; for learning Jenkins, what matters is thatnpm run buildgeneratesdist/.
.gitignore
Creating the Repository
If you have Node installed (18 or later):
If not, use a container, as you did with Maven in 01-04:
npm install: downloads Jest intonode_modules/and generatespackage-lock.json, which pins the exact version of each dependency. You must commit it to the repository: in Jenkins we will usenpm ci, which requires that file and installs exactly what it says, without updating anything. That is the guarantee that the build is reproducible.npm testshould showTests: 7 passed, 7 total.
Then create the repository on GitHub and push it:
git init -b main
git add .
git commit -m "Initial version of catalog-web"
git remote add origin https://github.com/<your-username>/catalog-web.git
git push -u origin mainThe NodeJS Plugin and Node Installations
The jenkins/jenkins:lts-jdk21 image comes with Java and Git, but not Node. Instead of installing it by hand in the container, we will use the NodeJS plugin, which downloads and manages Node versions as Jenkins tools, just as we saw with tools in 03-04.
- Manage Jenkins → Plugins → Available plugins, search for
NodeJS, select it and install it. - Manage Jenkins → Tools, NodeJS installations section → Add NodeJS:
| Field | Value |
|---|---|
| Name | node-18 |
| Install automatically | Checked |
| Install from nodejs.org → Version | The latest 18.x in the drop-down list |
| Global npm packages to install | (empty) |
- Repeat with Add NodeJS for
node-20(latest 20.x) andnode-22(latest 22.x). Save.
- The name is what the
Jenkinsfiles will use; that is why it is stable (node-20) and does not include the exact version: Laura can upgrade to the latest 20.x without touching anyJenkinsfile. - The first time a build uses an installation, the plugin downloads Node onto the node, inside
tools/injenkins_home. Subsequent builds reuse it.
Node 18 and Node 20 have already reached the end of their official support. TecnoShop keeps them in the matrix because it still has older environments that use them, and the matrix is precisely the tool that lets it migrate safely: as long as there are environments on Node 18, any change that breaks compatibility is caught before it reaches them. In exercise 3 you will add a current version.
The plugin offers two ways of using an installation in a pipeline:
tools { nodejs 'node-22' }: a declarative directive; it adds Node to thePATHfor the whole pipeline or stage. Ideal when the version is fixed.nodejs(nodeJSInstallationName: ...) { }: a step that adds Node to thePATHonly inside the block. It accepts a computed value, so it is the one we will use inside the matrix.
The matrix Directive
parallel runs different branches written by hand. matrix runs the same stages for each combination of values of one or more axes. Each combination is called a cell, and the cells run in parallel.
stage('Tests per Node version') {
matrix {
axes {
axis {
name 'NODE_VERSION'
values 'node-18', 'node-20', 'node-22'
}
}
agent any
stages {
stage('Test') {
steps {
echo "Testing with ${NODE_VERSION}"
}
}
}
}
}axes { axis { ... } }: the axes. Eachaxishas aname(which will be an environment variable inside the cell) and itsvalues.agent anyinsidematrix: each cell requests its own executor and its own workspace. We will come back to this shortly.stages { ... }: the stages repeated in each cell, in sequence.- Inside the cell, the axis value is read as an environment variable:
${NODE_VERSION}orenv.NODE_VERSION.
An axis with 3 values produces 3 cells. With two axes, you get the product: for example, 3 Node versions × 2 browsers = 6 cells. To rule out combinations that make no sense, you use excludes. This example is illustrative (TecnoShop does not have browser tests yet):
matrix {
axes {
axis {
name 'NODE_VERSION'
values 'node-18', 'node-20', 'node-22'
}
axis {
name 'BROWSER'
values 'chromium', 'firefox'
}
}
excludes {
exclude {
axis {
name 'NODE_VERSION'
values 'node-18'
}
axis {
name 'BROWSER'
values 'firefox'
}
}
}
stages {
stage('E2E') {
steps {
echo "Node ${NODE_VERSION} with ${BROWSER}"
}
}
}
}- An
excluderemoves the cells that meet all its axis conditions: here, only thenode-18+firefoxcombination. That leaves 5 cells. - Besides
values, inside anexcludeyou can usenotValuesto express "any value except these". matrixalso supportswhen(to skip cells based on a condition),environment,options,toolsandpost.
Why agent Goes Inside matrix
If the matrix does not declare an agent, all cells run in the same workspace at the same time. With npm that would be a disaster: npm ci deletes node_modules/ and reinstalls it, so three cells doing it simultaneously would destroy each other's work. It is the same problem as target/ with Maven, only guaranteed.
With agent any in the matrix, each cell gets its own workspace (catalog-web-pipeline, catalog-web-pipeline@2...) and its own checkout. And since there are 3 cells and 2 executors, the third one waits in the queue until another one finishes. That is why, so as not to waste an executor, the catalog-web pipeline will use a global agent none.
The catalog-web Jenkinsfile and the catalog-web-pipeline Job
Create the Jenkinsfile at the root of catalog-web:
pipeline {
agent none
options {
timestamps()
timeout(time: 20, unit: 'MINUTES')
buildDiscarder(logRotator(numToKeepStr: '30', artifactNumToKeepStr: '5'))
}
stages {
stage('Tests per Node version') {
matrix {
axes {
axis {
name 'NODE_VERSION'
values 'node-18', 'node-20', 'node-22'
}
}
agent any
stages {
stage('Test') {
steps {
nodejs(nodeJSInstallationName: env.NODE_VERSION) {
sh 'node --version && npm --version'
sh 'npm ci'
sh 'npm test'
}
}
post {
cleanup {
cleanWs()
}
}
}
}
}
}
stage('Build') {
agent any
tools {
nodejs 'node-22'
}
steps {
sh 'npm ci'
sh 'npm run build'
archiveArtifacts artifacts: 'dist/**', fingerprint: true
}
post {
cleanup {
cleanWs()
}
}
}
}
post {
success {
echo "OK: catalog-web #${env.BUILD_NUMBER} tested on Node 18, 20 and 22 and built."
}
failure {
echo "ERROR: catalog-web #${env.BUILD_NUMBER} failed. Check which matrix cell is red."
}
}
}The reasoning behind the decisions:
agent none: the pipeline does not hold an executor; each cell and theBuildstage request their own.nodejs(nodeJSInstallationName: env.NODE_VERSION): each cell uses the installation its axis specifies.sh 'node --version && npm --version': records in the log which version was actually used; if something fails on a single version, it is the first thing you will want to see.- No
failFastin the matrix: in compatibility testing you want to see all the versions. If onlynode-18fails, that fact is the information. post { cleanup { cleanWs() } }in each cell and inBuild: since each one has its own workspace, each one cleans its own. The pipeline'sposthas no agent, which is why it cannot clean anything here.Buildwithtools { nodejs 'node-22' }: the final artifact is built with a single version, the one TecnoShop uses in production.npm ciis repeated because this workspace is different from the cells' workspaces.archiveArtifacts artifacts: 'dist/**': archives all ofdist/, includingbuild.json.
Commit and push the Jenkinsfile. Then create the job:
- New Item →
catalog-web-pipeline→ Pipeline → OK. - Pipeline → Definition:
Pipeline script from SCM; SCM:Git; Repository URL:https://github.com/<your-username>/catalog-web.git; Branch Specifier:*/main; Script Path:Jenkinsfile. - Save and Build Now.
The first build will take longer, because it downloads the three Node versions. Watch the Build Executor Status panel while it runs: you will see two cells using the two executors and the third one in the queue with a message such as Waiting for next available executor. This job is temporary: in Multibranch Pipelines you will replace it with a multibranch job named catalog-web.
parallel vs. matrix
| Aspect | parallel |
matrix |
|---|---|---|
| What it runs | Different branches, written one by one | The same stages for each combination |
| How many branches | As many as you write | The product of the axis values, minus the excluded ones |
| Per-branch variables | Whatever you define in each branch | One environment variable per axis, automatically |
| Ruling out combinations | Not applicable | excludes |
| Typical use case | Tests + analysis + documentation at the same time | Testing on several versions of Node, Java, operating systems or browsers |
| At TecnoShop | Checks in orders-api |
Tests per Node version in catalog-web |
Keep in mind that large matrices generate a lot of code internally: with dozens of cells and many stages per cell, you may run into the Method code too large error. If that happens, reduce the stages per cell or move logic into scripts.
Parallelism in Scripted Pipelines (Comparison)
A scripted pipeline has neither a declarative parallel { } nor matrix: you build a map of name → block and pass it to the parallel step. This is how the catalog-web matrix would be written:
def versions = ['node-18', 'node-20', 'node-22']
def branches = [:]
for (v in versions) {
def version = v
branches[version] = {
node {
checkout scm
nodejs(nodeJSInstallationName: version) {
sh 'npm ci && npm test'
}
}
}
}
parallel branchesbranches = [:]: an empty map. Each entry will be a parallel branch.def version = v: essential. If the blocks usedvdirectly, they would all see its last value (node-22) when they run, and the three branches would test the same version. Copying the value into a new variable on each iteration makes each block "remember" its own.node { checkout scm ... }: in scripted syntax, each branch requests its executor and downloads the code explicitly.parallel branches: runs all entries at the same time. For fail-fast behavior, addbranches.failFast = true.
It is more flexible (branches can be computed dynamically from any data), but more error-prone. At TecnoShop, matrix covers the needs with declarative syntax.
Visualization in Pipeline Graph View
Open a build of orders-api-pipeline or catalog-web-pipeline and go to Pipeline Overview (the view provided by Pipeline Graph View):
- Parallel branches are drawn stacked vertically between the previous stage and the next one; the matrix appears with one cell per combination, identified by its axis value.
- Each branch has its own status color: green, red, gray (aborted by
failFastor skipped). - Clicking a branch shows only its log, without the mix of lines from the full console. It is the most convenient way to diagnose a failure in a specific branch.
The old Stage View also shows parallel branches, but less clearly, and it does not represent matrices well.
The Updated orders-api Jenkinsfile
Only the stages part changes: the Tests stage becomes a branch of Checks. Everything else (options, parameters, triggers, post) stays as in 04-01.
pipeline {
agent any
options {
timestamps()
timeout(time: 20, unit: 'MINUTES')
buildDiscarder(logRotator(numToKeepStr: '30', artifactNumToKeepStr: '5'))
disableConcurrentBuilds()
preserveStashes(buildCount: 5)
}
parameters {
booleanParam(name: 'RUN_TESTS', defaultValue: true,
description: 'Uncheck only to quickly verify that the code compiles. Never for a build that is going to be deployed.')
choice(name: 'ENVIRONMENT', choices: ['dev', 'staging', 'production'],
description: 'Target environment. For now only dev has a deployment, and it is simulated.')
}
triggers {
cron('TZ=Europe/Madrid\nH 2 * * 1-5')
pollSCM('TZ=Europe/Madrid\nH/15 * * * *')
}
stages {
stage('Build') {
steps {
echo "Build ${env.BUILD_NUMBER} of ${env.JOB_NAME} | ENVIRONMENT=${params.ENVIRONMENT} | RUN_TESTS=${params.RUN_TESTS}"
sh './mvnw -B clean compile'
}
}
stage('Checks') {
failFast true
parallel {
stage('Tests') {
when {
expression { params.RUN_TESTS }
}
options {
timeout(time: 10, unit: 'MINUTES')
}
steps {
sh './mvnw -B test'
}
post {
failure {
echo 'The tests failed: check the log of this stage (reports in target/surefire-reports).'
}
}
}
stage('Dependency analysis') {
options {
timeout(time: 5, unit: 'MINUTES')
}
steps {
sh label: 'Dependency tree', script: './mvnw -B dependency:tree -DoutputFile=dependencies.txt'
archiveArtifacts artifacts: 'dependencies.txt'
}
}
}
}
stage('Package') {
steps {
sh './mvnw -B -DskipTests package'
script {
def version = sh(script: './mvnw -q help:evaluate -Dexpression=project.version -DforceStdout',
returnStdout: true, label: 'Read the version from the pom').trim()
def date = sh(script: 'date -u +%Y-%m-%dT%H:%M:%SZ', returnStdout: true, label: 'Build date').trim()
currentBuild.description = "orders-api ${version}"
def lines = [
'application=orders-api',
"version=${version}",
"commit=${env.GIT_COMMIT}",
"build=${env.BUILD_NUMBER}",
"job=${env.JOB_NAME}",
"date=${date}",
"url=${env.BUILD_URL}"
]
writeFile file: 'build-info.txt', text: lines.join('\n') + '\n'
}
archiveArtifacts artifacts: 'target/*.jar,build-info.txt', fingerprint: true
stash name: 'jar', includes: 'target/*.jar'
}
}
stage('Smoke') {
options {
timeout(time: 3, unit: 'MINUTES')
}
steps {
dir('smoke') {
deleteDir()
unstash 'jar'
sh label: 'Start the jar and check that it responds', script: '''
JAR=$(ls target/*.jar)
PORT=$((18090 + EXECUTOR_NUMBER))
java -jar "$JAR" --server.port=$PORT > smoke.log 2>&1 &
PID=$!
trap 'kill $PID 2>/dev/null || true' EXIT
for i in $(seq 1 30); do
if curl -sf "http://localhost:$PORT/actuator/health" | grep -q '"status":"UP"'; then
echo "Smoke OK: the application is responding on port $PORT (attempt $i)"
curl -sf "http://localhost:$PORT/api/orders" | grep -q 'SHIPPED'
exit 0
fi
sleep 2
done
echo "ERROR: the application did not start within 60 seconds"
cat smoke.log
exit 1
'''
}
}
}
stage('Deploy to dev') {
when {
allOf {
expression { params.ENVIRONMENT == 'dev' }
expression { params.RUN_TESTS }
}
}
steps {
unstash 'jar'
echo 'SIMULATION: this is where target/orders-api-1.0.0-SNAPSHOT.jar would be deployed to dev (real deployment in 06-06 and 07-03).'
}
}
}
post {
success {
echo "OK: orders-api #${env.BUILD_NUMBER} built successfully."
}
unstable {
echo "WARNING: orders-api #${env.BUILD_NUMBER} is unstable."
}
failure {
echo "ERROR: orders-api #${env.BUILD_NUMBER} failed. Check the red stage."
}
fixed {
echo 'orders-api is back to green after an earlier failure.'
}
cleanup {
cleanWs()
}
}
}Commit ("Parallelize tests and dependency analysis"), push and run a build. In Pipeline Overview you will see Tests and Dependency analysis in parallel, and dependencies.txt will appear among the artifacts.
Common Mistakes and Tips
- Two branches writing to the same directory (
target/,node_modules/): intermittent failures that are hard to reproduce. Choose tasks that do not collide or give them separate workspaces. dependency:analyzein parallel withtest: it looks read-only, but it compiles intotarget/. Read which phases a goal runs before parallelizing it.- A matrix without
agent: all cells in the same workspace. Withnpm ci, failures are guaranteed. - Cells stuck in the queue forever: with a global
agent anyplusagent anyin the matrix, the pipeline keeps one executor and the cells share the other. Use a globalagent nonewhen the stages declare their own agent. - Forgetting
package-lock.json:npm cifails with an error saying it needs a lockfile. Commit it to the repository. - A misspelled installation name in
nodejs(...)ortools: the build fails, saying that installation does not exist. It must match Manage Jenkins → Tools exactly. - A
forloop without copying the variable in scripted syntax: all branches use the last value. - Parallelizing everything: if your machine has few resources, two JVMs at once can take longer than running in sequence. Measure before and after.
- Tip: parallelize in this order of priority: first the slowest independent work (test suites), then the cheap work (analysis, reports).
Exercises
Exercise 1. Diego proposes adding a third branch, Javadoc, to Checks, with ./mvnw -B javadoc:javadoc. Before accepting it, Laura asks him to answer: does it write to target/? What risk does running it in parallel with Tests in the same workspace pose? Propose a safe alternative.
Exercise 2. In catalog-web, Diego adds this function to src/prices.js, along with its test, and pushes:
What do you think the matrix will show? Check it. What options does the team have?
Exercise 3. Add a current, officially supported Node version to the catalog-web matrix (first create its installation in Tools, for example node-24) and make the build mark a cell that fails only on node-18 as unstable instead of failed. Hint: catchError inside the cell and a condition on env.NODE_VERSION.
Solutions
Solution 1. Yes: javadoc:javadoc generates the documentation in target/ (in target/reports/apidocs or target/site/apidocs, depending on the plugin version) and, to do so, it needs to resolve and sometimes compile sources, so it may read classes that Tests is writing. There is a risk of intermittent failures. Alternatives: (a) run it in sequence, for example in Package, when nothing else is writing to target/; (b) once there are agents (05-01), give the branch its own agent so that it has its own workspace and checkout. Option (a) is the simplest today.
Solution 2. Array.prototype.toSorted exists starting with Node 20. The node-18 cell will fail with TypeError: products.toSorted is not a function, and the node-20 and node-22 cells will be green. Because the matrix has no failFast, it is clear that the problem is one of compatibility and not of the code in general. Options: (a) rewrite it with a compatible alternative, [...products].sort((a, b) => a.price - b.price), which copies the array before sorting it so as not to modify the original; (b) if TecnoShop decides to drop Node 18, remove node-18 from the matrix and raise engines.node to >=20. What must not be done is to ignore the red cell.
Solution 3.
axes {
axis {
name 'NODE_VERSION'
values 'node-18', 'node-20', 'node-22', 'node-24'
}
}
agent any
stages {
stage('Test') {
steps {
nodejs(nodeJSInstallationName: env.NODE_VERSION) {
sh 'npm ci'
script {
if (env.NODE_VERSION == 'node-18') {
catchError(buildResult: 'UNSTABLE', stageResult: 'UNSTABLE') {
sh 'npm test'
}
} else {
sh 'npm test'
}
}
}
}
}
}With 4 cells and 2 executors, they will run two at a time. If only node-18 fails, its cell turns yellow and the build finishes UNSTABLE; if any other one fails, the build fails. It is a reasonable way to handle a version being phased out: the problem stays visible without blocking the team. Remember that, as you saw in 03-05, it is best to always specify both results of catchError.
Conclusion
You have learned to shorten feedback time by running work at the same time. With parallel you declare different branches that run simultaneously, and you know that, without their own agent, they share the workspace: that is why orders-api runs Tests in parallel with a dependency:tree that does not write to target/, rather than with a dependency:analyze that would compile at the same time. You control what happens when a branch fails with failFast and parallelsAlwaysFailFast(), and you understand how parallelism consumes executors and resources on the built-in node. With matrix, axes, axis, excludes and one agent per cell, catalog-web is tested on Node 18, 20 and 22 thanks to the NodeJS plugin, and you have compared all of this with the branch map of a scripted pipeline. The pipelines are starting to fill up with repeated values: the version, the Maven arguments, image names... In the next lesson, Using Environment Variables, you will learn to define them only once, compute them and understand their scope and pitfalls properly.
