Chapter 10: Jenkins Introduction
10.12 Lab — Jenkins in Docker + Pipeline job
Why: the problem
Now we put the whole chapter together. Suppose you join an Infosys project on Monday. The lead says: "Set up a Jenkins lab, add a pipeline for our badge API, make it test on every push, break it once and show me you can read the red log." This is a real first-week task. In this lab you do exactly that, end to end: Jenkins in Docker, a Jenkinsfile in Git, a Pipeline job from SCM, a green build, a red build on purpose, a fix, and a clean shutdown. Do every step yourself. Typing it is how it stays in your memory.
What we will build
You will build the full lab: Jenkins LTS in Docker with a named volume, a badge API repo in Python and Node.js variants with a Jenkinsfile, a Pipeline job from SCM with Poll SCM, a green run, a red run, a fix, test reports and a cleanup.
What: every term in plain English
- Lab — A practice setup you can break and rebuild.
- badge API — A tiny service that returns a user badge. Our sample app in this course.
- Checkout stage — Gets the code from Git.
- Test stage — Runs the tests. Red if any test fails.
- JUnit report — An XML file of test results Jenkins can draw as a graph.
- Green / red — SUCCESS / FAILURE result of a build.
- Poll SCM — Jenkins checks Git for new commits on a timer.
- Teardown — Clean shutdown at the end.
How: step by step
-
Start Jenkins
docker volume create jenkins_home && docker run -d --name jenkins -p 127.0.0.1:8080:8080 -v jenkins_home:/var/jenkins_home ravi/jenkins-lab:1.0What it does: The custom image from 10.3 has Python and plugins.
Output
a71c... -
Unlock and create admin
docker exec jenkins cat /var/jenkins_home/secrets/initialAdminPassword, then finish the wizardWhat it does: Admin user ravi.
Output
Jenkins is ready! -
Create the repo
mkdir badge-api && cd badge-api && git init -b mainWhat it does: Add the files from Example 1.
Output
Initialized empty Git repository -
Push to your Git server
git add . && git commit -m "badge api with Jenkinsfile" && git remote add origin https://git.example.com/ravi/badge-api.git && git push -u origin mainWhat it does: Jenkins will read from here.
Output
main -> main -
Create the job
New Item > badge-api > Pipeline > Pipeline script from SCM > Git > URL > */main > Save > Build NowWhat it does: Build #1 runs the Jenkinsfile from Git.
Output
Finished: SUCCESS
Example 1: Python badge API with tests and a Jenkinsfile
Stack. Python 3, pytest, Jenkins LTS
Goal. Python badge API with tests and a Jenkinsfile.
app/badge.py
def badge(points):
if points >= 1000:
return "gold"
if points >= 500:
return "silver"
return "bronze"
tests/test_badge.py
from app.badge import badge
def test_gold():
assert badge(1200) == "gold"
def test_silver():
assert badge(600) == "silver"
def test_bronze():
assert badge(10) == "bronze"
Jenkinsfile
pipeline {
agent any
triggers { pollSCM('H/5 * * * *') }
options {
timeout(time: 10, unit: 'MINUTES')
buildDiscarder(logRotator(numToKeepStr: '20'))
}
stages {
stage('Checkout') { steps { checkout scm } }
stage('Test') {
steps {
sh 'python3 -m venv .venv && . .venv/bin/activate && pip install -q pytest && python -m pytest -q --junitxml=report.xml'
}
post { always { junit 'report.xml' } }
}
}
post {
success { echo 'badge-api is green' }
failure { echo 'badge-api is red: open the Test stage log' }
always { cleanWs() }
}
}
What each line does
badge(points)— Returns gold, silver or bronze.--junitxml=report.xml— Writes results in JUnit format.junit 'report.xml'— Jenkins draws a test trend from it.pollSCM('H/5 * * * *')— New commits build within about 5 minutes.cleanWs()— Clean workspace after each build.
Green output
Started by user ravi
Obtained Jenkinsfile from git https://git.example.com/ravi/badge-api.git
[Pipeline] { (Test)
+ python -m pytest -q --junitxml=report.xml
... [100%]
3 passed in 0.03s
Recording test results
badge-api is green
Finished: SUCCESS
Expected result. Build #1 is green and the job page shows a Test Result Trend.
Example 2: Break it on purpose, read the red log, fix it
Stack. pytest, Poll SCM
Goal. Break it on purpose, read the red log, fix it.
app/badge.py (broken change)
def badge(points):
if points > 1000:
return "gold"
if points >= 500:
return "silver"
return "bronze"
tests/test_badge.py (new edge test)
from app.badge import badge
def test_gold_edge():
assert badge(1000) == "gold"
fix.sh
sed -i 's/points > 1000/points >= 1000/' app/badge.py
git commit -am "fix: 1000 points is gold" && git push
What each line does
points > 1000— The bug: exactly 1000 points becomes silver.test_gold_edge— A test for the edge value catches it.sed -i ...— Puts back the >= sign.git push— Poll SCM starts a new build.
Green output
Build #2 (Started by an SCM change)
+ python -m pytest -q --junitxml=report.xml
F...
FAILED tests/test_badge.py::test_gold_edge - AssertionError: assert 'silver' == 'gold'
1 failed, 3 passed in 0.05s
badge-api is red: open the Test stage log
Finished: FAILURE
Build #3 (Started by an SCM change)
4 passed in 0.03s
Finished: SUCCESS
Expected result. You saw red with the exact failing test, fixed one character, and got green again. This is CI doing its job.
Example 3: Node
Stack. Node.js 20, Docker agent
Goal. Node.js variant of the same lab.
badge.js
function badge(points) {
if (points >= 1000) return 'gold';
if (points >= 500) return 'silver';
return 'bronze';
}
module.exports = { badge };
badge.test.js
const test = require('node:test');
const assert = require('node:assert');
const { badge } = require('./badge');
test('gold', () => assert.strictEqual(badge(1000), 'gold'));
test('silver', () => assert.strictEqual(badge(600), 'silver'));
package.json
{ "name": "badge-api", "version": "1.0.0", "scripts": { "test": "node --test --test-reporter=junit --test-reporter-destination=report.xml" } }
Jenkinsfile
pipeline {
agent { docker { image 'node:20-alpine' } }
stages {
stage('Checkout') { steps { checkout scm } }
stage('Test') {
steps { sh 'npm test' }
post { always { junit 'report.xml' } }
}
}
}
What each line does
node --test— Built-in test runner.--test-reporter=junit— Node 20 writes JUnit XML too.agent { docker { image 'node:20-alpine' } }— Needs the Docker setup from 10.8.junit 'report.xml'— Same test graph as Python.
Green output
+ npm test
> badge-api@1.0.0 test
> node --test --test-reporter=junit --test-reporter-destination=report.xml
Recording test results
Finished: SUCCESS
Expected result. Same lab, another language. Only the test lines changed.
Verify: did it work?
-
Check the test graph
Job page > Test Result TrendWhat it does: Shows build #2 red and #3 green.
Output
#1 3 pass #2 1 fail #3 4 pass -
Check triggers
Build #3 > first lineWhat it does: It was started by Git, not by you.
Output
Started by an SCM change
When it is red 1
ERROR: Test reports were found but none of them are new
Cause. The report file is old or the path is wrong.
Fix, step by step
- Write report.xml in each build.
- cleanWs at the end so old files go.
- Check the junit path.
When it is red 2
python3: not found
Cause. Plain jenkins image without Python.
Fix, step by step
- Use ravi/jenkins-lab from 10.3, or a python Docker agent.
When it is red 3
No changes; build not started by Poll SCM
Cause. The commit was not pushed, or the branch differs.
Fix, step by step
- git push and check git log origin/main.
- Branch Specifier must be */main.
- Wait 5 minutes or click Build Now.
Cleanup
-
Stop and keep or delete
docker stop jenkins (keep) or bash teardown.sh from 10.11 (delete with backup)What it does: Never leave the lab running.
Output
jenkins
Ravindra Bagale's Tip
Type this lab yourself — no copy-paste. See a red build, fix it, make it green. That is real experience!
हा lab स्वतः type करून करा, copy-paste नको. Red build बघा, fix करा, green करा. हाच खरा अनुभव!
यह lab खुद type करके करो, copy-paste नहीं. Red build देखो, fix करो, green करो. यही असली अनुभव है!
Practice tasks
Easy Add a lint stage
Why: More checks.
What to do: Add flake8 or eslint before Test.
- pip install flake8 && flake8 app
Check: Stage View shows Lint.
Medium Add a Docker image stage
Why: Real delivery.
What to do: Build a badge-api image on main only.
- when { branch 'main' }
- docker build -t badge-api:$BUILD_NUMBER .
Check: Image exists on the agent.
Hard Move to Multibranch
Why: Team flow.
What to do: Recreate the job as a Multibranch Pipeline and open a PR.
- Use 10.8b steps.
Check: A PR job runs.
Easy Say the Jenkins lab in two lines
Why: If you can say it simply, you understand it. Juniors and interviewers both want the short version first.
What to do: Write two short lines about the Jenkins lab for a fresher who knows only Linux, Git and Docker basics.
- Write the problem it solves.
- Write the one Jenkins screen, Jenkinsfile line or command you use for it.
- Read it aloud to a friend.
Check: A fresher understands it without asking a question.
Easy Keep a throwaway lab Jenkins
Why: Practice needs a Jenkins you can break. If the lab gets messy, you delete the container and volume and start again.
What to do: Run a lab Jenkins in Docker on your laptop with a named volume jenkins_home.
- docker volume create jenkins_home
- docker run -d --name jenkins -p 8080:8080 -v jenkins_home:/var/jenkins_home jenkins/jenkins:lts-jdk17
- Open http://localhost:8080 and finish the setup wizard.
Check: The Jenkins dashboard opens and shows "Welcome to Jenkins!".
Medium Do it on a second stack
Why: A pipeline idea must work for Node.js, Python and Java. Only the build and test lines should change.
What to do: Repeat this lesson with a different language than the one you used first.
- If you used Python, use Node.js or Maven now.
- Change only the sh lines for build and test.
- Keep the same stage names.
Check: Same green result, and the stage names did not change.
Medium Break it on purpose
Why: You must know the red console log by face. In a real outage there is no time to read slowly.
What to do: Cause one error from the "When it is red" part of this lesson and fix it.
- Follow the error section.
- Copy the exact message from Console Output into your notes.
- Write the fix in one line.
Check: You fixed it using only the steps, without searching the web.
Medium Write a one-page runbook
Why: At 2 a.m. nobody remembers Jenkins menus. A short page saves the on-call person.
What to do: Write a one-page runbook for this lesson.
- Title, when to use, exact clicks or Jenkinsfile lines, how to check, how to undo.
Check: A teammate can follow it alone.
Hard Explain it like an interview
Why: Interviewers want real stories, not definitions.
What to do: Record a 60 second answer about this lesson.
- Say the problem, the Jenkinsfile lines you wrote, and one error you hit.
Check: Your answer has a real Jenkinsfile line and a real error message.
Hard Draw the flow top to bottom
Why: A drawing shows the order of work and which stage waits for which.
What to do: Draw this lesson as boxes from top to bottom.
- Start at git push or Build Now, go through each stage, end at the green build or the deployed app.
Check: Each box matches a real line in your Console Output.
Homework: try at home
Try at home
At home, do the full lab in Python, then repeat it in Node.js. Save screenshots of build #2 red and #3 green with the Test Result Trend.
Recap
- Jenkins in Docker with a named volume is the lab base.
- The Jenkinsfile lives in Git; the job reads it from SCM.
- Poll SCM builds new commits.
- JUnit reports give test graphs.
- Break, read, fix, and then stop or tear down.
FAQ
Can I do this lab without a Git server?
Use a local bare repo path or a free Git host account.
Why both Python and Node?
To see that only the test lines change.
How long should it take?
About 60 to 90 minutes the first time.
What if Docker agents fail?
Use the Python variant on ravi/jenkins-lab first.
Can I show this in interviews?
Yes. Explain the red build and the fix.
Interview questions
-
Walk me through setting up a Jenkins pipeline.
Run Jenkins, add credentials, write a Jenkinsfile with checkout and test stages, create a Pipeline from SCM job, add triggers, run, read results.
-
How do you show test results in Jenkins?
Write JUnit XML from the test tool and use the junit step.
-
How did you debug a failing build?
Read the Console Output, found the failing assert, fixed the code, pushed, and the next build was green.
-
Why poll or webhook?
So every push is tested without a human clicking Build.
-
What do you do after a lab?
Back up JENKINS_HOME if needed, stop or delete containers and cloud resources.
Quick quiz
Q1. Which option writes JUnit XML in pytest?
--junitxml=report.xml.
Q2. Which step reads it?
junit.
Q3. What started build #2?
An SCM change from Poll SCM.
Q4. What was the bug?
> instead of >= for 1000 points.
Q5. What do you do after the lab?
Stop Jenkins, or back up and tear down.
Lab
Run Jenkins and execute a Pipeline for badge API tests.
- Start Jenkins LTS with a named volume; complete unlock + admin user.
- Confirm UI loads on your published host counter (local laptop preferred).
- Add a
Jenkinsfileto your badge API repo with at leastCheckoutandTeststages (pytestornpm test). - Create a Pipeline job → Pipeline script from SCM pointing at that repo.
- Run a build; save a note of Console Output lines from a green Test stage.
- Intentionally break a test, push, rebuild — confirm the stage goes red and the log shows the assertion.
- Fix the test; rebuild green.
- When done:
docker stop jenkins(and remove if you want); keep or deletejenkins_homevolume intentionally.
Practice task
Write a short table (five rows) mapping your Chapter 9 Actions workflow pieces to Jenkinsfile equivalents (on, job, run, secrets, SHA tag build).
Thodkyaat sangaycha tar
- Jenkins remains common in enterprises; learn controller/agent and Pipeline-as-code.
- Prefer Declarative
Jenkinsfilein Git over only Freestyle clicks. - Credentials store holds secrets — not the repo.
- Same CI stages as Actions; different YAML/Groovy syntax and hosting model.
- Harden lab Jenkins (auth, SG, no open UI); stop idle containers.
- Debug with Console Output the same way you read Actions logs.
Did you understand? Let us try it once more.
Revision card
Interview card