Jenkins Lesson 1: Core Fundamentals

From docker compose up to your first green build: controller / agent / executor / queue, the setup wizard, plugins, job types, Jenkinsfile, credentials, and finally testing myapp, packaging it as an image and archiving it
Jenkins LTS 2.580.2Weekly 2.590Java 21 / 25Docker Compose · Gitea 28.4Verified against jenkins.io · 2026-11-16
Prerequisites This lesson is the fourth course in the CI/CD platform group of the DevOps learning path (Linux → Bash → Git → Docker → Kubernetes → Terraform → Ansible → GitHub → GitLab → Azure DevOps → Jenkins → AKS → Helm → GitOps and Argo CD → Prometheus & Grafana), where you pick one or two courses from the group. Before you start, make sure you have mastered Git 8-hour course branches, remotes and authentication. If you have taken GitHub Actions or Azure Pipelines, this lesson compares them in the “Theory” tab without repeating their content. For container and image details, see Docker 8-hour course, and this lesson directly reuses the sample app myapp from it.
Overall learning goals
  • Map out Jenkins’ runtime architecture: controller, agent, node, executor, queue (Queue), label, workspace, and JENKINS_HOME, and be able to walk through every step of “one build from trigger to result” (this lesson’s core animation).
  • Set up a local lab environment with Docker Compose ~/jenkinslab: jenkins (controller,jenkins/jenkins:2.580.2-jdk21),agent1 (inbound agent, label linux docker),gitea (local Git server, repo lab/myapp). Lesson 2 continues directly on this environment.
  • Work through the setup wizard, and understand the difference between LTS and weekly, the Java 21/25 requirements, the plugins no longer bundled with the WAR from 2.580.1 onward, and why the built-in node should be set to 0 executors.
  • Understand the plugin system: the Update Center offers compatible versions by core version, dependency resolution,requiredCore, installation/upgrade/rollback, and using plugins.txt + jenkins-plugin-cli to pin plugin versions.
  • Distinguish Freestyle, Pipeline, Multibranch Pipeline, Organization Folder, and write your first Declarative Jenkinsfile (agent / stages / steps / post / options).
  • Create and use credentials gitea-myapp (Gitea username + access token), understand credential scope,withCredentials log masking, and the “Groovy string interpolation leaking secrets” warning.
  • Run myapp as a full CI: pytest + JUnit report → docker build build the myapp:1.0 → smoke test /healthz → archive the artifacts and add fingerprints; finally, check the environment with the 12-item readiness review and troubleshooting tree.

1-hour time allocation table

#TimeModuleCore contentAnimation / interactionLab (~/jenkinslab)
0Before classEnvironment setupcompose.yaml (jenkins / agent1 / gitea), Gitea user lab and repo lab/myapp, myapp source and test pushEnvironment self-check checklistThree containers running,lab/myapp code present
100–06Jenkins architecturecontroller / agent / node / executor / queue / label / workspace; built-in node with 0 executors; agent → controller securityCore animation: the lifecycle of a buildCreate node agent1 and connect it
206–13Installation and setupLTS vs weekly, Java 21/25, image tags,JENKINS_HOME, initialAdminPassword, setup wizard, Jenkins URLFirst startup and wizard sequenceUnlock, create admin, generate API token
313–21Plugin systemUpdate Center, dependencies and requiredCore, suggested plugins, plugins split out in 2.580.1, security advisories, version pinningPlugin dependency resolverInstall the Gitea and Docker Pipeline plugins, export plugins.txt
421–28Job typesFreestyle, Pipeline, Multibranch, Organization Folder, folders; configuration stored in config.xmlJob type selector + branch indexingCreate a Freestyle comparison and a Pipeline job myapp
528–35Your first JenkinsfileDeclarative structure, agent label, stage/steps, options, environment, post condition orderJenkinsfile line-by-line executorCommit the Jenkinsfile and run your first green build
635–42Credentials and security basicsCredential types and scopes, encrypted storage, withCredentials, masking, interpolation warnings, least-privilege tokensCredential resolution and maskingCreate gitea-myapp, and call the Gitea API securely
742–50Build myapppytest + junit, docker build, smoke test, archiveArtifacts, fingerprint, UNSTABLE and FAILUREStage view simulatorBuild the myapp:1.0 and archive the report
850–60Readiness review and troubleshooting basics12-item build readiness review; stuck queue, agent offline, authentication failure, docker.sock permissions, test failureInteractive troubleshooting treeDeliberately create 4 faults and fix them
—After classCheat sheet · Integrated labTurn manual configuration into a repeatable script and verify itFinal quiz (12 questions)Integrated lab

Knowledge Coverage Matrix

Target skillM1M2M3M4M5M6M7M8Key commands / UILab
Explain controller / agent / executor / queue✓··✓✓·✓✓/queue/api/json,/computer/api/jsonM1, M8
Docker installation and JENKINS_HOME management·✓✓··✓·✓docker compose,initialAdminPasswordModule 0, M2
Connect and manage agents, labels✓✓··✓·✓✓jenkins/inbound-agent,-url … secret nameM1
Plugin installation, dependencies and version pinning·✓✓····✓install-plugin,jenkins-plugin-cliM3
Choose job types, manage config.xml···✓✓·✓·create-job,get-jobM4
Write a Declarative Jenkinsfile···✓✓✓✓✓declarative-linter,build -s -vM5, M7
Credential creation, binding and masking···✓·✓✓✓withCredentials,create-credentials-by-xmlM6
Test reports, image builds, artifact archiving····✓·✓✓junit,archiveArtifacts,docker buildM7, integrated lab
Build troubleshooting✓✓✓·✓✓✓✓Console logs,docker compose logs, node logsM8 troubleshooting tree

What this lesson leaves out (and where to learn it)

TopicWhy it is not in this lessonWhere to learn it
Multibranch hands-on, webhook triggers, parallel, matrix, Shared Library, CPS and persistence internalsCore Pipeline materialLesson 2
Pushing images to ACR / ECR, cloud credentials and managed identitiesRequires a cloud subscriptionLesson 3 (Azure), Lesson 4 (AWS)
Configuration as Code (JCasC), deploying Jenkins with Helm, Kubernetes Pod agentsRequires first understanding every manual configuration itemLesson 5
SSO (OIDC/SAML/Entra), matrix/role authorization, Script Security approvalBelongs to enterprise security and governanceLesson 6
Performance tuning, thread dumps, queue depth troubleshooting, backup and restore drillsBelongs to advanced troubleshootingLesson 7
Dockerfile best practices, multi-stage builds, image security scanningCovered in the Docker courseDocker 8-hour course
GitHub Actions and Azure Pipelines themselvesCovered in other courses; this lesson only compares themGitHub course · Azure DevOps course

How to use this courseware

10 pages per module
Theory · Diagram · Animation · Commands · Lab · Production case · Troubleshooting · Quiz · Voice · Video. We suggest reading “Theory” and “Animation” first, then doing the “Lab”. The “build lifecycle” animation in Module 1 is the core of this lesson, and every later module returns to it.
Learning progress
A quiz score of 70% or higher, or clicking “Mark this module complete”, counts toward progress, saved in this browser’s local storage (if the browser blocks local storage, it is cleared on refresh).
Chinese voice
The “Voice” tab uses the browser’s built-in Web Speech API (en-US) to read the narration aloud; if no Chinese voice pack is installed, the narration script can still be read, or passed to a TTS tool to generate audio.
Version notes Verified 2026-11-16. The current LTS is 2.580.2 (released 2026-10-28; 2.580.1 was released 2026-09-30),weekly is 2.590 (2026-11-09). Jenkins supports Java 21 and Java 25; starting with 2.555.1 LTS, Java 21 or later is required and Java 17 is no longer supported (the last LTS to support Java 17 is 2.541.3). The lab image is pinned to jenkins/jenkins:2.580.2-jdk21, the agent image is jenkins/inbound-agent:3395.v6e5377b_0fb_3c-5-jdk21, and Gitea is gitea/gitea:28.4 (starting with 28.0, Gitea dropped the “1.” prefix from its version numbers, so the former 1.28 is now 28.0). For plugin versions, follow the compatible versions the Update Center provides for 2.580.2 at install time (see Module 3). A new LTS baseline comes out roughly every 12 weeks; read the LTS upgrade guide.

Module 0 · Environment setup (complete before class)

In ~/jenkinslab use Docker Compose to start the three services jenkins, agent1 and gitea, create the Gitea user lab and the private repo lab/myapp, and push the myapp source and tests
Before class ≈ 20 minAll runs locally · freeagent1 mounts docker.sock: lab use only
Prerequisites
  • An Ubuntu 24.04 VM or workstation (recommended, consistent with the Docker course), or Docker Desktop on macOS / Windows 11 + WSL2. Available memory ≥ 4 GB, disk ≥ 15 GB.
  • Installed Docker Engine 29 and Docker Compose v2 (docker compose version), and the current user can run docker. For installation instructions, see Docker course.
  • Installed Git 2.4x,curl,python3 (used only for local JSON formatting, optional). Ports 8080, 50000 and 3000 on this machine are free.
  • If you have completed the Docker course ’s myapp is better; if you do not have it, that is fine, and the full source code is given below (Flask + gunicorn + Redis counter, port 5000,/healthz).

Directory structure (at the end of this lesson)

~/jenkinslab/
├── compose.yaml            # jenkins, agent1, gitea: three services
├── .env                    # DOCKER_GID, AGENT1_SECRET (permissions 600, do not commit)
├── agent/Dockerfile        # adds python3 and docker CLI on top of the official inbound-agent
├── .secrets/               # gitea-token, jenkins-token (permissions 700, do not commit)
└── myapp/                  # pushed to the lab/myapp repo in Gitea
    ├── app.py  requirements.txt  requirements-dev.txt  pytest.ini
    ├── tests/test_app.py
    ├── Dockerfile  .dockerignore
    └── Jenkinsfile         # first version written in Module 5, full version in Module 7

Step 1: create directories and the agent image

The official jenkins/inbound-agent image only has Java and remoting (agent.jar), with no Python or Docker CLI. We add two things on top of it: the python3, and the docker CLI (copied from the official docker:29-cli image: static binary and buildx plugin).

mkdir -p ~/jenkinslab/{agent,myapp/tests,.secrets} && cd ~/jenkinslab
chmod 700 .secrets

cat > agent/Dockerfile <<'EOF'
# agent1: official inbound agent (JDK 21) + python3 + docker CLI
FROM jenkins/inbound-agent:3395.v6e5377b_0fb_3c-5-jdk21
USER root
RUN apt-get update \
 && apt-get install -y --no-install-recommends python3 python3-venv python3-pip git curl \
 && rm -rf /var/lib/apt/lists/*
# Only copy the client: the daemon is still dockerd on the host (accessed through the mounted docker.sock)
COPY --from=docker:29-cli /usr/local/bin/docker /usr/local/bin/docker
COPY --from=docker:29-cli /usr/local/libexec/docker/cli-plugins/docker-buildx /usr/local/libexec/docker/cli-plugins/docker-buildx
USER jenkins
EOF

Step 2: compose.yaml

cat > compose.yaml <<'EOF'
name: jenkinslab

services:
  jenkins:                                   # controller: schedules only, does not build
    image: jenkins/jenkins:2.580.2-jdk21
    container_name: jenkins
    restart: unless-stopped
    ports:
      - "127.0.0.1:8080:8080"                # Web UI / REST / CLI (bound to localhost only)
      - "127.0.0.1:50000:50000"              # inbound agent TCP port (only needed for agents outside compose)
    environment:
      JAVA_OPTS: "-Xms512m -Xmx1g"
    volumes:
      - jenkins_home:/var/jenkins_home       # all configuration, jobs, build records, plugins, secrets
    networks: [ci]

  agent1:                                    # permanent inbound agent, labels linux docker
    build: ./agent
    image: jenkinslab/agent1:jdk21
    container_name: agent1
    restart: unless-stopped
    init: true
    depends_on: [jenkins]
    # Consistent with the official README: -url <controller> -workDir=<directory> <secret> <agent name>
    command: ["-url", "http://jenkins:8080", "-workDir=/home/jenkins/agent", "${AGENT1_SECRET:-not-set}", "agent1"]
    group_add:
      - "${DOCKER_GID:-999}"                 # lets the jenkins user access docker.sock
    volumes:
      - agent1_work:/home/jenkins/agent      # workspace and remoting cache
      - /var/run/docker.sock:/var/run/docker.sock   # ⚠ equivalent to host root privileges, lab use only
    networks: [ci]

  gitea:                                     # local Git server: user lab, repo lab/myapp
    image: gitea/gitea:28.4
    container_name: gitea
    restart: unless-stopped
    environment:
      USER_UID: "1000"
      USER_GID: "1000"
      GITEA__database__DB_TYPE: sqlite3
      GITEA__server__ROOT_URL: http://localhost:3000/
      GITEA__server__DISABLE_SSH: "true"
      GITEA__security__INSTALL_LOCK: "true"   # skip the web install page
      GITEA__service__DISABLE_REGISTRATION: "true"
      GITEA__webhook__ALLOWED_HOST_LIST: "private"   # the Lesson 2 webhook must be sent to jenkins (private address)
    ports:
      - "127.0.0.1:3000:3000"
    volumes:
      - gitea_data:/data
    networks: [ci]

volumes:
  jenkins_home:
  agent1_work:
  gitea_data:

networks:
  ci:
EOF

# .env: read automatically by compose. DOCKER_GID takes the group of docker.sock as seen inside the container; applies to both Linux and Docker Desktop
echo "DOCKER_GID=$(docker run --rm -v /var/run/docker.sock:/s alpine:3.22 stat -c %g /s)" > .env
echo "AGENT1_SECRET=" >> .env
chmod 600 .env
docker compose config --quiet && echo "compose.yaml OK"
compose.yaml OK
Security trade-off: why agent1 mounts docker.sock Mounting /var/run/docker.sock gives anyone who can run sh docker commands in agent1 the ability to docker run -v /:/host --privileged … obtain host root. We do this so that Lesson 1 can focus on Jenkins itself: the lab has only you as a user, ports are bound only to 127.0.0.1 localhost, and do not run untrusted code. Alternatives for production: ① a dedicated build VM as the agent (the isolation boundary is the VM); ② rootless Docker or docker:dind a sidecar (the approach used in the official Docker install guide, but it requires --privileged); ③ build tools that do not need a daemon (BuildKit rootless, Kaniko-style tools); ④ the ephemeral Kubernetes Pod agents from Lesson 5. Whichever option you choose,do not mount docker.sock on the controller, and do not build on the controller.

Step 3: start jenkins and gitea

agent1 needs a secret, which only exists after you create the node in Jenkins (Module 1), so first start only the other two services, and build the agent image in the meantime:

docker compose build agent1
docker compose up -d jenkins gitea
docker compose ps
# wait for Jenkins to finish its first-time initialization (about 30–60 seconds)
until docker compose logs jenkins 2>&1 | grep -q "Jenkins is fully up and running"; do sleep 3; done
docker compose exec jenkins cat /var/jenkins_home/secrets/initialAdminPassword
NAME      IMAGE                          SERVICE   STATUS          PORTS
gitea     gitea/gitea:28.4               gitea     Up 20 seconds   127.0.0.1:3000->3000/tcp, 22/tcp
jenkins   jenkins/jenkins:2.580.2-jdk21  jenkins   Up 20 seconds   127.0.0.1:8080->8080/tcp, 127.0.0.1:50000->50000/tcp
3f1c9a4e0b7d4e2c9a6b1f0d8e7c5a21

Open http://localhost:8080, and paste the 32-character initial password shown above. The setup wizard pages that follow are explained page by page in Module 2; if you want to finish setting up the environment first, follow the shortest path below:

  1. Customize Jenkins → Install suggested plugins (recommended plugins: 19, about 90 including dependencies; wait 2–5 minutes).
  2. Create First Admin User: Username admin, set a strong password, and for email enter admin@example.com.
  3. Instance Configuration: keep the Jenkins URL as http://localhost:8080/ → Save and Finish → Start using Jenkins.

Step 4: create user lab, an access token and a private repo in Gitea

cd ~/jenkinslab
read -rsp "Set the password for Gitea user lab: " GITEA_PASS; echo
# 1) create the admin user lab with the Gitea admin command (must run as the git user inside the container)
docker compose exec -u git gitea gitea admin user create \
  --username lab --password "$GITEA_PASS" --email lab@example.com \
  --admin --must-change-password=false

# 2) generate a repo-only access token for Jenkins (read/write repo: Lesson 2 needs it to write commit statuses back)
# -T: do not allocate a TTY, to avoid a trailing \r polluting the token file
docker compose exec -T -u git gitea gitea admin user generate-access-token \
  --username lab --token-name jenkins-myapp --scopes write:repository \
  | awk '{print $NF}' > .secrets/gitea-token
chmod 600 .secrets/gitea-token
GITEA_TOKEN=$(cat .secrets/gitea-token)

# 3) create the private repo lab/myapp via the API (default branch main)
curl -s -u "lab:$GITEA_PASS" -H "Content-Type: application/json" \
  -X POST http://localhost:3000/api/v1/user/repos \
  -d '{"name":"myapp","private":true,"default_branch":"main","description":"Jenkins 8h course sample app"}' \
  | python3 -c 'import sys,json; d=json.load(sys.stdin); print(d["full_name"], d["private"], d["clone_url"])'
New user 'lab' has been successfully created!
lab/myapp True http://localhost:3000/lab/myapp.git
Do not mix up the two URLs The clone address shown by Gitea is http://localhost:3000/lab/myapp.git (ROOT_URL, for your browser and host machine). Jenkins and agent1 are on the compose network, for them localhost means the container itself, so you must use the service name http://gitea:3000/lab/myapp.git. This is the most common cause of clone failures in this lesson (see Module 8).

Step 5: myapp source, tests and Dockerfile

cd ~/jenkinslab/myapp
cat > app.py <<'EOF'
import os
import socket

import redis
from flask import Flask

app = Flask(__name__)
r = redis.Redis(host=os.getenv("REDIS_HOST", "redis"), port=6379, socket_connect_timeout=1)


@app.get("/")
def index():
    try:
        hits = r.incr("hits")
    except redis.exceptions.RedisError:
        hits = "N/A (redis not connected)"
    return f"Hello from {socket.gethostname()}, hits={hits}\n"


@app.get("/healthz")
def healthz():
    return {"status": "ok"}
EOF

cat > requirements.txt <<'EOF'
flask==3.1.*
redis==5.*
gunicorn==23.*
EOF

cat > requirements-dev.txt <<'EOF'
-r requirements.txt
pytest==9.*
EOF

cat > pytest.ini <<'EOF'
[pytest]
pythonpath = .
testpaths = tests
EOF

cat > tests/test_app.py <<'EOF'
import redis

import app as appmod


def test_healthz():
    resp = appmod.app.test_client().get("/healthz")
    assert resp.status_code == 200
    assert resp.get_json() == {"status": "ok"}


def test_index_without_redis(monkeypatch):
    class Down:
        def incr(self, key):
            raise redis.exceptions.ConnectionError("redis down")

    monkeypatch.setattr(appmod, "r", Down())
    resp = appmod.app.test_client().get("/")
    assert resp.status_code == 200
    assert b"N/A" in resp.data
EOF

cat > Dockerfile <<'EOF'
# syntax=docker/dockerfile:1
FROM python:3.13-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app.py .
RUN useradd -m appuser
USER appuser
EXPOSE 5000
HEALTHCHECK CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:5000/healthz')" || exit 1
CMD ["gunicorn", "-b", "0.0.0.0:5000", "app:app"]
EOF

cat > .dockerignore <<'EOF'
.git
.venv
__pycache__
.pytest_cache
reports
tests
Jenkinsfile
EOF

cat > .gitignore <<'EOF'
.venv/
__pycache__/
.pytest_cache/
reports/
EOF

Compared with the myapp from the Docker course, only three things are added: /healthz returns JSON,tests/ the two pytest cases under (the second case uses monkeypatch to simulate Redis being unavailable, so CI does not need Redis),pytest.ini in the pythonpath = . (otherwise import app will report ModuleNotFoundError).

Step 6: push to Gitea

cd ~/jenkinslab/myapp
git init -b main
git add . && git commit -m "myapp: Flask app, tests and Dockerfile"
git remote add origin http://localhost:3000/lab/myapp.git
# the token is only placed in the HTTP header of this one command, and is not written to .git/config or the remote URL
AUTH=$(printf 'lab:%s' "$(cat ../.secrets/gitea-token)" | base64 | tr -d '\n')
git -c http.extraHeader="Authorization: Basic $AUTH" push -u origin main
git ls-remote origin
To http://localhost:3000/lab/myapp.git
 * [new branch]      main -> main
branch 'main' set up to track 'origin/main'.
9b2f6c1d0e4a8b7c3f5d2e1a0c9b8d7e6f5a4b3c	HEAD
9b2f6c1d0e4a8b7c3f5d2e1a0c9b8d7e6f5a4b3c	refs/heads/main

Future pushes can keep using the same git -c http.extraHeader=… push, or follow Git course to configure a credential helper.

Environment self-check checklist

Cost, permissions and cleanup Everything runs locally, with no cloud costs. You need permission to run Docker (members of the docker group are effectively root, so only do this on your own lab machine). To pause: docker compose stop; full cleanup (this deletes all Jenkins configuration, build records and Gitea repos): docker compose down -v && docker image rm jenkinslab/agent1:jdk21 myapp:1.0. Lesson 2 continues using this environment, so after finishing this lesson do not run down -v.

Module 1 · Jenkins architecture: controller, agent, executor and queue

00:00 – 06:00 · the controller is responsible for “deciding where to run”, and the agent is responsible for “actually running”; in between are the queue, labels and executors
6 minLTS 2.580.2built-in node: 0 executors★★★★★
Learning objectives
  • Explain controller, node, agent, executor, label, queue, workspace, JENKINS_HOME the eight concepts and how they relate.
  • Describe the full lifecycle of a build: trigger → enter queue (waiting / blocked / buildable) → label matching → assign executor → workspace → step execution → log and artifact return → result.
  • Understand why the official guidance recommends not building on the built-in node, and the significance of agent → controller access control (always enabled since 2.326).
  • Create the permanent node agent1 in the lab environment (label linux docker) and connect it via inbound.
Prerequisites: Basic concepts of containers, ports and volumes. Importance:★★★★★ (the seven modules and seven lessons that follow are all built on this model)

What: what Jenkins is

Jenkins is an open-source automation server (MIT license, written in Java, community hosted by the CD Foundation), distributed as a WAR file and able to run on Docker, Kubernetes, Linux/Windows/macOS. By itself it only provides scheduling, the Job model, the Web UI, REST/CLI and a security framework; nearly all of the “doing things” features — Git pulls, Pipeline, credentials, Docker, Kubernetes — come from plugins (Module 3).

ConceptWhat it isIn the lab environment
controller (formerly called master)The Jenkins main process: stores configuration, provides the UI/API, maintains the queue, schedules builds, runs the Groovy logic of Pipelines, and stores logs and artifactsContainer jenkins
nodethe generic name for machines that can execute builds, including the built-in node and each agentBuilt-In Node, agent1
agentvia remoting (agent.jar), a remote node that connects to the controller and actually runs sh,git,docker buildContainer agent1
executora “build slot” on a node, i.e. one execution thread. A node with N executors can run N builds at the same time (or Pipeline node blocks)agent1: 2; built-in node: 0
labelA label on a node; builds use label expressions (such as linux && docker) to declare what kind of node they needagent1: linux docker
queueThe list of tasks waiting to run; each task passes in turn through waiting (quiet period) → blocked (being blocked) → buildable (waiting for a free executor)/queue/api/json
workspaceThe directory on a node assigned to a Job; code checkout and builds happen here, and it is kept between builds by default/home/jenkins/agent/workspace/myapp
JENKINS_HOMEThe controller’s data directory: config.xml, jobs/, builds/, plugins/, secrets/, credentials.xml, nodes/volume jenkins_home → /var/jenkins_home

Why: why separate the controller and the agents

  • Security: the official docs Controller Isolation state that any build running on the built-in node has the same access to the controller’s filesystem as the Jenkins process — build scripts can read secrets/ and all credentials. Therefore, the official guidance is to “strongly recommend against running any build on the built-in node.”
  • Stability: the controller is a single point of failure; when builds compete for its CPU, memory and disk I/O, the UI lags, the queue stalls, and even OOM can interrupt all builds. The official node documentation recommends setting the controller’s executor count to 0, so builds run only on agents.
  • Heterogeneity and scaling: Linux, Windows, macOS, GPU and ARM each have their own agents, distinguished by labels; when more capacity is needed, add agents rather than scaling up the controller.

How: how agents connect to the controller

MethodWho initiatesNetwork requirementsBest for
Inbound TCP (inbound, used in this lesson)the agent connects to the controllerfirst accesses HTTP(S) to get the port and identity, then connects to the TCP inbound port (default 50000 in the official image)agents behind NAT/firewalls, containers, ephemeral Pods
Inbound WebSocketthe agent connects to the controlleronly needs the controller’s HTTP(S) port, not 50000a reverse proxy/load balancer in front of the controller, only 443 open
SSH (SSH Build Agents plugin)controller connects to agentthe controller can SSH to the agent, and the agent has Javafixed Linux build machines
Cloud / dynamic (Kubernetes, EC2 Fleet, Azure VM and similar plugins)plugins create agents on demand and destroy them afterwardsdepends on the cloudelastic capacity (Lessons 4 and 5)

Once the connection is established, the controller and agent share a bidirectional remoting channel: the controller sends requests such as “run this process, read this file” to the agent, and the agent streams output back to the controller. Agent → Controller access control Prevents agents from sending malicious commands back to the controller; always enabled since 2.326, and the official guidance strongly recommends not bypassing it.

When: when more agents / more executors are needed

  • If the queue often shows “Waiting for next available executor” → insufficient capacity: add agents, or, when CPU/memory has headroom, raise a single agent’s executors from 1 to 2–4.
  • If the queue shows “There are no nodes with the label …” → the label is wrong or that type of agent is missing; adding executors will not help.
  • A memory-hungry build (such as a Docker build or Java compilation) → 1 executor per agent is more stable; lightweight script-type tasks can run several.

Comparison with GitHub Actions and Azure Pipelines

JenkinsGitHub ActionsAzure Pipelines
controller (self-hosted)GitHub-hosted serviceAzure DevOps-hosted service
agent + executorrunner (each runner runs one job at a time)agent (each agent runs one job at a time) + parallel job licenses
label expression linux && dockerruns-on: [self-hosted, linux]pool + demands
Queue (in controller memory)jobs queue waiting for a runnerjobs queue waiting for an agent and parallel job capacity
Jenkinsfile (Groovy DSL).github/workflows/*.ymlazure-pipelines.yml

See GitHub course and Azure DevOps course. The biggest difference: you run the Jenkins controller yourself (upgrades, plugins, backups, security); it is flexible, but all of the responsibility is yours too.

Common misconceptions① “Setting executors equal to the CPU core count is fine”—— executors are the number of concurrent builds; a single Docker build or Java compilation can saturate multiple cores, and blindly adding executors makes them slow each other down. ② “A Pipeline itself takes up an executor”—— the Groovy part of a Declarative Pipeline runs on the controller in a lightweight (flyweight) way and does not occupy a node’s executor; only agent / node blocks take up an executor on an agent. ③ “Renaming master is just a word change”—— 2.307 (LTS 2.319.1) renamed the master node to the built-in node, and at the same time changed its label from master to built-in; new installs take effect directly, while older instances upgraded to this version need the administrator to apply the migration manually from the prompt; Jobs that depend on the old label master need to be adjusted. ④ “The workspace is deleted once the build finishes”—— it is kept by default unless you use cleanWs() or the Workspace Cleanup plugin.

Architecture diagram: lab environment ~/jenkinslab

Docker Compose project jenkinslab · network ci · host exposes only 127.0.0.1 jenkins (controller) · jenkins/jenkins:2.580.2-jdk21 Web UIREST / CLI :8080 Queuewaiting→buildable Pipeline engineGroovy (CPS) Built-In Nodeexecutors = 0 (no builds) TCP inbound port:50000 (JNLP4-connect) volume jenkins_home → /var/jenkins_homeconfig.xml · jobs/*/builds/N/{log,archive} · plugins/ · secrets/ · credentials.xml · nodes/ agent1 · jenkinslab/agent1:jdk21 Labels: linux docker · usage: only runs Jobs whose labels match executor #0 executor #1 remotingagent.jar Workspace: /home/jenkins/agent/workspace/myapp Tools: git · python3 · docker CLI (→ host docker.sock) ① agent connects actively: HTTP discovery → TCP 50000 gitea · gitea/gitea:28.4 Repo lab/myapp (private) In-container address http://gitea:3000 Host http://localhost:3000 Host dockerd /var/run/docker.sock builds myapp:1.0 ⚠ mounting means root privileges ② git fetch ③ docker build the controller also accesses Gitea: lightweight checkout of the Jenkinsfile → Browser → 127.0.0.1:8080 (Jenkins), 127.0.0.1:3000 (Gitea)
Figure 1-1: the controller only schedules and stores; builds run on agent1; the agent connects to the controller actively, so the agent does not need to expose any ports

Workflow diagram: components a build passes through

Triggeruser / REST /cron/webhook Queue5-second quiet periodblocked? Label matchlinux && docker→ agent1 executoragent1 #0Leave queue WorkspaceLock directorycheckout scm Stepssh / junit /docker build LogsArtifacts→ ctrl ResultSUCCESSpost Typical reasons for getting stuck here (Module 8 / Lesson 7) no node with a matching label · all executors busy · node offline blocked by disableConcurrentBuilds · throttling (Throttle) Where it is written on disk (the controller’s JENKINS_HOME) jobs/myapp/builds/1/log · build.xml · junitResult.xml jobs/myapp/builds/1/archive/** · fingerprints/
Figure 1-2: the three stages before the queue decide “whether it can start”, and the stages after it decide “what the result is”; logs and artifacts are ultimately stored on the controller

Core animation: the lifecycle of a build

Using a Pipeline Job myapp (in the Jenkinsfile agent { label 'linux && docker' }) as an example. Each step highlights the corresponding component, and the right side shows the real state of the queue item (corresponding to /queue/api/json fields), and the terminal below shows the real output you would see in the console log. Choose different scenarios to see at which step the build gets stuck and what it reports.

① TriggerPOST /job/myapp/build ② Enter queuewaiting / blocked ③ Label matchlinux && docker ④ Assign executoragent1 #0 ⑤ Workspaceworkspace/myapp ⑥ Run stepscheckout · sh · junit ⑦ Logs / artifacts→ JENKINS_HOME ⑧ Result— controller: ② ③ ④ are handled by the Queue maintenance thread; the Pipeline’s Groovy runs on the controller’s lightweight executor agent1: ⑤ ⑥ run on the agent; output streams back to the controller via the remoting channel (⑦)
Queue item / execution status
(not yet triggered)
Ready. After choosing a scenario, click “Play” or “Next step”.
$ curl -X POST -u admin:$JENKINS_TOKEN http://localhost:8080/job/myapp/build
The real mechanics behind the animation Jenkins’ hudson.model.Queue represents the task as WaitingItem (during the quiet period) → BlockedItem (blocked by other builds or resources) → BuildableItem (can run, waiting for an executor) → leaves the queue and becomes LeftItem (with executable set to the build number). In a Pipeline, the agent block submits another placeholder task “part of myapp #N”, which likewise goes through label matching and executor assignment; this is why “Still waiting to schedule task” appears in Pipeline logs.

Command table

Command / interfacePurposeKey parameters
GET /computer/api/jsonLists all nodes, online status, executor count and labelstree=computer[displayName,offline,numExecutors,assignedLabels[name]]
GET /queue/api/jsonShows the status and reason of each item in the queue (why)tree=items[id,task[name],why,blocked,buildable,stuck,inQueueSince]
GET /computer/agent1/jenkins-agent.jnlpGets the connection parameters of an inbound agent (including the secret); requires the node’s Connect permissionauthenticates with an API token
docker compose logs agent1View remoting handshake and disconnect reasons-f,--since 10m
CLI list-computers/offline-node/online-nodenode management (Jenkins CLI; see the jcli function in Module 2)-m "reason"
cd ~/jenkinslab
JT=$(cat .secrets/jenkins-token)       # admin API token generated in the Module 2 lab
curl -s -u "admin:$JT" "http://localhost:8080/computer/api/json?tree=computer[displayName,offline,numExecutors,assignedLabels[name]]" | python3 -m json.tool
{
  "_class": "hudson.model.ComputerSet",
  "computer": [
    { "displayName": "Built-In Node", "numExecutors": 0, "offline": false,
      "assignedLabels": [ { "name": "built-in" } ] },
    { "displayName": "agent1", "numExecutors": 2, "offline": false,
      "assignedLabels": [ { "name": "agent1" }, { "name": "docker" }, { "name": "linux" } ] }
  ]
}

How to verify: A node’s own name is also a label (agent1), so agent { label 'agent1' } you can pin a build to a specific node (not recommended, as it loses scheduling flexibility). Common errors: 401 returned → wrong token or username; 403 returned → that user does not have Overall/Read. Production use: A monitoring script periodically checks offline: true nodes and raises alerts.

# Watch the queue: run this right after triggering a build
curl -s -u "admin:$JT" "http://localhost:8080/queue/api/json?tree=items[id,task[name],why,blocked,buildable,stuck]" | python3 -m json.tool
{
  "items": [
    { "id": 17, "task": { "name": "part of myapp #4" },
      "why": "There are no nodes with the label ‘windows’",
      "blocked": false, "buildable": true, "stuck": false }
  ]
}

stuck: true means the item has been runnable for a long time but never gets an executor (typically no online node matches its label), making it a good alerting metric.

Goal: Set the built-in node to 0 executors, create the permanent node agent1, and connect it via inbound. Environment: Module 0 has started jenkins and gitea, and the setup wizard has been completed. Cost: None.

Set the built-in node to 0 executors: Manage Jenkins → Nodes → Built-In Node → Configure → Number of executors change to 0 → Save. From then on, no build will run on the controller.
Create node agent1: Manage Jenkins → Nodes → New Node → Name agent1, type Permanent Agent → Create, then fill in:
FieldValueNotes
Number of executors2Runs at most 2 builds at the same time
Remote root directory/home/jenkins/agentMatches the -workDir path and volume in compose
Labelslinux dockerSpace-separated multiple labels
UsageOnly build jobs with label expressions matching this nodeJobs without a label will not run here
Launch methodLaunch agent by connecting it to the controllerInbound
AvailabilityKeep this agent online as much as possibleDefault
Get the secret and write it to .env: after saving, open the node page http://localhost:8080/computer/agent1/, which shows the connection command; the 64-character hexadecimal string in it is the secret.
cd ~/jenkinslab
read -rsp "Paste agent1's secret: " S; echo
sed -i "s/^AGENT1_SECRET=.*/AGENT1_SECRET=$S/" .env      # macOS: sed -i '' …
# or via the API (requires the Module 2 API token): the secret is the first argument in the JNLP file
curl -s -u "admin:$(cat .secrets/jenkins-token)" http://localhost:8080/computer/agent1/jenkins-agent.jnlp \
  | sed -n 's|.*<argument>\([0-9a-f]\{64\}\)</argument>.*|\1|p'
Start agent1 and watch the handshake:
docker compose up -d agent1
docker compose logs agent1 | tail -n 15
agent1  | INFO: Locating server among [http://jenkins:8080/]
agent1  | INFO: Agent discovery successful
agent1  |   Agent address: jenkins
agent1  |   Agent port:    50000
agent1  | INFO: Handshaking
agent1  | INFO: Connecting to jenkins:50000
agent1  | INFO: Trying protocol: JNLP4-connect
agent1  | INFO: Remote identity confirmed: 4a:91:...:c2
agent1  | INFO: Connected
Verify: on the Nodes page, agent1 shows as online with 2 idle executors; Built-In Node has no executors. Then verify that agent1 can access Docker:
docker compose exec agent1 id
docker compose exec agent1 docker version --format '{{.Client.Version}} / {{.Server.Version}}'
docker compose exec agent1 python3 --version
uid=1000(jenkins) gid=1000(jenkins) groups=1000(jenkins),988
29.10.0 / 29.10.0
Python 3.13.5

The 988 in groups is the DOCKER_GID in .env (it differs per machine). The Python version depends on the inbound-agent base image (Debian).

Cleanup: no cleanup; later modules all use agent1.

Case 1: controller OOM takes down the whole platform

Problem: Early on, the team built directly on the controller (built-in node with 4 executors); a large parallel Maven build exhausted memory, the Jenkins process was killed by the OOM Killer, all of the 30+ running builds were interrupted, and the UI was down for 20 minutes. Fix: Set the built-in node executors to 0; add 3 Linux agents with 2 executors each; size the controller’s JVM heap per the official hardware recommendations, and monitor it separately. Configuration: Nodes → Built-In Node → executors 0; all Jobs explicitly write agent { label 'linux' }. Limitation: Older Freestyle Jobs have no label restriction; you need to batch-add “Restrict where this project can be run”.

Case 2: agents behind a firewall connect using WebSocket

Problem: The controller is deployed behind a load balancer that only opens 443, and the security team is unwilling to open port 50000. Fix: Switch the agent to WebSocket mode (using the -webSocket parameter), so only HTTPS is used. Limitation: The reverse proxy must correctly support WebSocket upgrades and a long idle timeout, otherwise the connection will drop periodically.

Case 3: use labels to distinguish capabilities rather than machines

Problem: A Job hard-codes label 'build-server-03', so when that machine is under maintenance all builds queue up. Fix: Label by capability (linux,docker,jdk21,arm64), and Jobs write an expression linux && docker, so machines of the same kind back each other up. Limitation: Labels need a naming convention and an inventory, otherwise you will end up with Docker and docker such case mismatches (labels are case-sensitive).

Common errors and fixes

SEVERE: http://jenkins:8080/ provided port:50000 is not reachable on host jenkins

Cause: The agent can reach HTTP but cannot connect to the inbound TCP port: the port is disabled (Security → Agents → TCP port for inbound agents set to Disable), the port number differs, or a firewall blocks it.

curl -sI http://localhost:8080/tcpSlaveAgentListener/ | grep -i x-jenkins-jnlp-port
docker compose exec agent1 bash -c 'timeout 3 bash -c "</dev/tcp/jenkins/50000" && echo open'

Fix: Enable fixed port 50000 (already enabled by default in the official image); or switch to WebSocket (adding -webSocket to the compose command).

SEVERE: The server rejected the connection: None of the protocols were accepted / Unauthorized access

Cause: The secret is wrong (copied incorrectly, or changed after the node was deleted and recreated), or the node name does not match the secret.

grep AGENT1_SECRET ~/jenkinslab/.env | cut -c1-25
docker compose logs agent1 --since 5m | grep -iE "secret|rejected|unauthor"

Fix: Get the secret again from the node page, update .env, then docker compose up -d agent1 (compose will recreate the container because the parameters changed).

The build keeps showing “Waiting for next available executor on ‘Built-In Node’”

Cause: The Job has no label (or has written built-in), while the built-in node has 0 executors; agent1 only runs Jobs whose labels match.

Fix: Write in the Jenkinsfile agent { label 'linux && docker' }; for Freestyle Jobs, tick “Restrict where this project can be run” and enter the label.

agent1 is offline: Agent went offline during the build / java.nio.channels.ClosedChannelException

Cause: The agent container restarts or is killed by OOM, the network drops, or the controller restarts.

docker compose ps agent1
docker inspect agent1 --format '{{.State.OOMKilled}} {{.RestartCount}}'
docker compose logs agent1 --since 15m | tail -n 30

Fix: Give Docker enough memory; the agent’s restart: unless-stopped will reconnect automatically; an interrupted Pipeline must be rerun (Lesson 2 covers how Pipelines recover after a controller restart).

Command-line questions
1. Using a single curl command, list the names of all offline nodes.
curl -s -u "admin:$JT" "http://localhost:8080/computer/api/json?tree=computer[displayName,offline]" \
  | python3 -c 'import sys,json; print([c["displayName"] for c in json.load(sys.stdin)["computer"] if c["offline"]])'
2. Check why each item in the queue is still waiting.
curl -s -u "admin:$JT" "http://localhost:8080/queue/api/json?tree=items[task[name],why]" | python3 -m json.tool
Scenario analysis question
A Jenkins instance has only a controller (built-in node with 2 executors); the team wants to run Docker builds on it and also wants to mount docker.sock into the controller container. Assess the risks and propose a redesign.

Risk: when builds run on the built-in node, they can read JENKINS_HOME/secrets the controller’s files and all credentials; mounting docker.sock on top of that gives anyone who can edit the Jenkinsfile host root. Plan: set the built-in node executors to 0; add separate agents (dedicated VMs or containers) and provide Docker on the agents (ideally a dedicated build VM or a rootless / ephemeral Pod approach); have Jobs use labels linux && docker to target; the controller exposes only the necessary ports, and back up JENKINS_HOME.

Verified teaching videos

▶
What Is Jenkins? | What Is Jenkins And How It Works? | Jenkins Tutorial For Beginners | Simplilearn — Simplilearn
English · introductory concepts: continuous integration and Jenkins’ distributed controller/agent architecture (the video still uses the old master/slave terms)
▶
Learn Jenkins! Complete Jenkins Course - Zero to Hero — DevOps Journey
English · full introductory course, including demos of agents and the build flow; the version is older, so follow this lesson for the UI and version numbers

Official docs

Video storyboard script (about 90 seconds)

This courseware cannot generate video/MP3 directly; the storyboard and narration script are provided, to be passed to a video tool for generation.

Shot 1 · 0–15s
Visual: a large box “controller” containing the UI, queue and JENKINS_HOME; beside it, two small boxes “agent1” and “agent2”.
Narration: Jenkins is split into two parts: the controller schedules and stores everything, and agents actually run the builds.
Shot 2 · 15–40s
Visual: click Build Now; a card enters the queue and passes through two gates, “quiet period” and “label match”.
Narration: the build first enters the queue, waits for the quiet period to end, then looks for a node with a matching label and a free executor.
Shot 3 · 40–65s
Visual: the card lands in an executor slot on agent1, the workspace directory expands, the terminal scrolls sh output, and the output flows back to the controller along the arrow.
Narration: the steps run in the agent’s workspace, and logs stream back to the controller in real time to be saved.
Shot 4 · 65–90s
Visual: the built-in node’s executor slot is marked with a red cross and “0”.
Narration: with the built-in node’s executors set to zero, build scripts cannot touch the controller’s keys and configuration.
or score ≥ 70% in the “Quiz”

Module 2 · Installation and setup: LTS, Docker image and setup wizard

06:00 – 13:00 · choose the right release line and image tag, understand JENKINS_HOME, complete the setup wizard, and get a Jenkins you can operate by script
7 minLTS 2.580.2 · Java 21/25Java 17 is no longer supported★★★★☆
Learning objectives
  • Distinguish the LTS and weekly release lines, and read official Docker image tags (2.580.2-jdk21,lts-jdk21,latest,slim,alpine,rhel-ubi9).
  • Know the Java support policy: Java 21 and 25 are supported; from 2.555.1 LTS onward, Java 21+ is required.
  • Understand what Jenkins does on first startup: generates initialAdminPassword, enters the installation state machine, installs suggested plugins, creates the admin user, and sets the Jenkins URL.
  • Recognize the JENKINS_HOME directory structure and know how to back up and upgrade it; generate an API token and configure the Jenkins CLI.
Prerequisites: The Module 0 jenkins container is running. Importance:★★★★☆

What: two release lines

LTS (Long-Term Support)Weekly
CadenceRoughly every 12 weeks, one weekly is picked as the new baseline (e.g. 2.580), followed by .1, .2 and .3 patch releasesOne release per week (2.588 → 2.589 → 2.590)
Current (as of 2026-11-16)2.580.2 (2026-10-28); 2.580.1 on 2026-09-302.590 (2026-11-09)
ContentOnly backports verified fixes and security patchesNew features and fixes; changes fastest
Docker tagslts,lts-jdk21,2.580.2-jdk21latest,jdk21,2.590-jdk21
Best forProduction (used throughout this course)Test instances that want to try new features early

Java support (official Java support policy page)

JavaFirst LTSFirst weeklyPlanned end of support
Java 252.541.1 (2026-01)2.534 (2025-10)2029-09
Java 212.479.1 (2024-10)2.463 (2024-06)2027-09
Java 17 (discontinued)the last LTS is 2.541.3 (2026-03) and the last weekly is 2.544; from 2.555.1 onward Java 21 or later is required, and the Java 17 controller image has been removed

Used in this lesson -jdk21 image; -jdk25 an equivalent image is also available. Note that Java 21 is planned to reach end of support in 2027-09; production environments should plan the switch to Java 25 before then (agents must be upgraded too, and it is recommended that the controller and agents use the same Java version).

How to choose an official image tag

TagMeaningRecommendation
2.580.2-jdk21Pinned LTS version + JDK 21 (Debian base)Preferred for production: repeatable and rollback-able
2.580.2-lts-jdk21Same as above, alias with the lts labelSame as above
lts-jdk21 / ltsFloating tag, always pointing to the latest LTSGood for learning; in production it would be upgraded without you knowing
latestLatest weeklyDo not use in production
-slim / -alpine / -rhel-ubi9Smaller Debian / Alpine / Red Hat UBI 9 basesChoose according to enterprise base image requirements
-windowsservercore-ltsc2022/2025Windows containersWindows 2019 images are no longer provided from 2.568.1 onward

How: what happens on first startup

  1. The container entrypoint script copies /usr/share/jenkins/ref/ the contents of (for example, plugins preinstalled in the image) into the empty JENKINS_HOME, then starts java -jar jenkins.war (embedded Jetty, port 8080).
  2. Jenkins finds JENKINS_HOME is brand new → install state is NEW → security is enabled and a random initial admin password is generated and written to secrets/initialAdminPassword and printed to the log.
  3. When accessed from a browser, it enters the setup wizard: Unlock Jenkins → choose plugins (suggested plugins or a custom selection) → download and install plugins and dependencies from the Update Center → create the first admin → set the Jenkins URL → run.
  4. Once complete, it writes jenkins.install.InstallUtil.lastExecVersion, the initial password file is deleted,initialAdmin and the setup account becomes invalid. On later startups Jenkins sees these files and does not enter the wizard again.

JENKINS_HOME directory structure (excerpt)

PathContentsBack up?
config.xmlGlobal configuration: security realm, authorization strategy, executor count, views, etc.Required
jobs/<name>/config.xmlConfiguration of each JobRequired
jobs/<name>/builds/<N>/build.xml, log, archive/, test resultsAs needed (may be very large)
nodes/<name>/config.xmlNode definitions (agent1’s labels, executor count)Required
credentials.xmlGlobal credentials (encrypted storage)Required, and secrets/ must be backed up at the same time
secrets/master.key,hudson.util.Secret and other encryption keysRequired, stored separately and encrypted
plugins/Installed .jpi and extracted directoriescan be rebuilt from plugins.txt
users/Local users, API tokens (hashed)Required
workspace/,caches/built-in node workspaces and cachesNot needed

When: how to choose an installation method

MethodBest forNotes
Docker / Compose (this lesson)Learning, single-node production, easy to upgrade and roll backJENKINS_HOME must be on a volume; the in-container user is UID 1000
Kubernetes Helm chartPlatform teams, combined with JCasCLesson 5
Linux packages (apt/yum, systemd)Traditional VMsJava must be installed and upgraded separately
Windows MSIMust run the controller on WindowsWindows 2019 users can only use MSI or a self-built image
Run the WAR directlyTemporary testingNot recommended for production
Common misconceptions① “Using latest is the most stable”——latest is a weekly. ② “Deleting and rebuilding the container loses the configuration”—— as long as the jenkins_home volume still exists, all configuration is kept; conversely,docker compose down -v will also delete the volume. ③ “If the initial password is lost, you have to reinstall”—— before the wizard is complete, you can find it in secrets/initialAdminPassword or in the container logs. ④ “Backing up only credentials.xml is enough to restore credentials”—— without secrets/ the keys in it, the credentials cannot be decrypted.

Sequence of first startup and setup wizard

Browser (you)jenkins containerJENKINS_HOME volumeUpdate Center updates.jenkins.io ① copy ref/ → empty volume; generate initialAdminPassword ② paste initial password (Unlock) ③ fetch update-center.json (filtered by core version 2.580.2) ④ download suggested plugins + dependencies (about 90 .jpi files) ⑤ write to plugins/, load dynamically ⑥ create admin, set Jenkins URL ⑦ users/admin_*/, config.xml, lastExecVersion RUNNING: wizard finished
Figure 2-1: the wizard only appears when JENKINS_HOME is a new volume; plugins come from the Update Center, and compatible versions are filtered by the current core version

Data flow for upgrade and rollback

Read the upgrade guide2.580.x notes Back up the volumetar jenkins_home Change the image tagpull + up -d Upgrade pluginsversions compatible with the new core Verifyadministrative monitors, smoke build On failure: switch back to the old tag and restore the backup
Figure 2-2: upgrading Jenkins means “swapping the WAR / swapping the image”; the data format migrates forward, so rolling back must rely on the backup taken before the upgrade

Animation: first startup and installation state machine

Jenkins uses jenkins.install.InstallState to record installation progress. Choose “a fresh volume” or “an existing volume” and observe whether the wizard appears and which files each step writes.

Ready.
$ docker compose up -d jenkins

Command table

CommandPurposeKey parameters
docker compose exec jenkins cat /var/jenkins_home/secrets/initialAdminPasswordGet the initial passwordThe file is deleted after the wizard completes
docker compose logs jenkinsstartup logs, plugin loading errors-f,--since
curl -sI http://localhost:8080/loginFrom the X-Jenkins response header, read the version—
java -jar jenkins-cli.jar -s URL …Jenkins CLI (HTTP mode)-auth or environment variable JENKINS_USER_ID / JENKINS_API_TOKEN
jcli version / who-am-i / helpVerify CLI and identity—
jcli safe-restartWait for running builds to finish before restarting—

Read the version and Jenkins CLI configuration

curl -sI http://localhost:8080/login | grep -i '^x-jenkins:'

# download the CLI matching the controller version (saved to the volume, so it survives container rebuilds)
cd ~/jenkinslab
docker compose exec jenkins curl -sSo /var/jenkins_home/jenkins-cli.jar http://localhost:8080/jnlpJars/jenkins-cli.jar

# define jcli: run the CLI in the jenkins container, passing the token via an environment variable (so it does not appear in CLI arguments)
jcli() {
  docker compose -f ~/jenkinslab/compose.yaml exec -T \
    -e JENKINS_USER_ID=admin -e JENKINS_API_TOKEN="$(cat ~/jenkinslab/.secrets/jenkins-token)" \
    jenkins java -jar /var/jenkins_home/jenkins-cli.jar -s http://localhost:8080/ "$@"
}
jcli version
jcli who-am-i
X-Jenkins: 2.580.2
2.580.2
Authenticated as: admin
Authorities:
  authenticated

How to verify:who-am-i Shows Authenticated as: admin; if it shows anonymous means the token was not passed in. Common errors:ERROR: You must authenticate to access this Jenkins.—— the token file is empty or the token has been revoked. Production use: Scripted export of Job configuration, batch starting and stopping of nodes, safe restarts. You can add the jcli function to ~/.bashrc, which later modules will all use.

Backup and upgrade

cd ~/jenkinslab
# back up (volume name = project name_volume name). In production, first put Jenkins into quiet mode: jcli quiet-down
docker run --rm -v jenkinslab_jenkins_home:/src:ro -v "$PWD":/backup alpine:3.22 \
  tar czf /backup/jenkins_home-$(date +%F).tgz -C /src --exclude=./workspace --exclude=./caches .
ls -lh jenkins_home-*.tgz

# upgrade (example: after the next LTS patch is released): change the tag → pull → rebuild the container; the volume stays unchanged
# sed -i 's|jenkins/jenkins:2.580.2-jdk21|jenkins/jenkins:<new version>-jdk21|' compose.yaml
docker compose pull jenkins && docker compose up -d jenkins
-rw-r--r-- 1 user user 92M Nov 16 10:20 jenkins_home-2026-11-16.tgz
The backup file contains keys The backup contains secrets/ and credentials.xml, and with it anyone can decrypt all credentials. Store it encrypted (for example age / gpg), and do not put it in a shared directory.

Goal: Confirm the setup wizard results, generate an API token for admin, configure jcli, and back up JENKINS_HOME once. Environment: Module 0 has completed the setup wizard. Cost: None.

Review every page of the wizard (if you have already completed Module 0, open the corresponding settings page to check):
Wizard pageWhat it didWhere to change it later
Unlock JenkinsProves you can read the container filesystem—
Customize JenkinsInstalls suggested plugins (Folders, Pipeline, Git, Credentials Binding, Timestamper, Workspace Cleanup, Pipeline Graph View, Matrix Authorization, SSH Build Agents, etc.)Manage Jenkins → Plugins
Create First Admin UserCreates in Jenkins’ built-in user database adminManage Jenkins → Users
Instance ConfigurationJenkins URL (used for links in emails and status write-backs)Manage Jenkins → System → Jenkins URL
Generate API token: top-right username admin → Security → API Token → Add new Token, name lab-cli → Generate → copy (shown only once).
cd ~/jenkinslab
read -rsp "Paste the admin API token: " T; echo
printf '%s' "$T" > .secrets/jenkins-token && chmod 600 .secrets/jenkins-token
curl -s -u "admin:$(cat .secrets/jenkins-token)" http://localhost:8080/whoAmI/api/json | python3 -m json.tool | head -n 6
{
    "_class": "hudson.security.WhoAmI",
    "anonymous": false,
    "authenticated": true,
    "authorities": [
        "authenticated"

Calling REST/CLI with an API token does not need a CSRF crumb; only sessions logged in with a password need one. Tokens can be revoked at any time on the same page.

Configure jcli: run the CLI download and jcli() function definition from the “Commands” tab, then:
jcli version
jcli list-plugins | wc -l
2.580.2
92
Take a look at JENKINS_HOME:
docker compose exec jenkins ls /var/jenkins_home
docker compose exec jenkins cat /var/jenkins_home/jenkins.install.InstallUtil.lastExecVersion; echo
docker compose exec jenkins ls /var/jenkins_home/secrets
config.xml  jenkins-cli.jar  jenkins.install.InstallUtil.lastExecVersion  jobs  nodes  plugins  secrets  updates  userContent  users ...
2.580.2
hudson.util.Secret  jenkins.model.Jenkins.crumbSalt  master.key  org.jenkinsci.main.modules.instance_identity.InstanceIdentity.KEY ...

Note secrets/ under it there is no longer initialAdminPassword: it is deleted once the wizard completes.

Back up once: run the backup command from the “Commands” tab and confirm you get jenkins_home-date.tgz, then move it to an encrypted location or delete it (for lab use).

Case 1: “weekend automatic upgrade” caused by a floating tag

Problem: The production compose uses jenkins/jenkins:lts, and on a weekend node restart it pulled a new LTS baseline; some older plugins were incompatible with the new core, so on Monday all Pipelines errored. Fix: Change to a pinned tag 2.580.2-jdk21, and upgrades go through a change process: read the upgrade guide → verify on a staging instance → back up → upgrade. Limitation: A pinned tag means you must actively track security advisories (the 2026-10-28 advisory includes a core fix); otherwise you stay exposed to vulnerabilities for a long time.

Case 2: offline environment installation

Problem: The internal network cannot reach updates.jenkins.io, and the wizard gets stuck at plugin installation. Fix: On a networked machine, preinstall plugins into a custom image (Module 3’s plugins.txt + jenkins-plugin-cli), push the image to the internal registry; or set up an internal Update Center mirror. Limitation: From 2.580.1 onward, several plugins (such as bouncycastle API, Instance Identity, JavaMail API, etc.) are no longer bundled in the WAR; offline instances must put these plugins into plugins/, otherwise it may fail to start.

Case 3: forced upgrade when Java 17 reaches end of support

Problem: A team was still running 2.541.x on a Java 17 VM in 2026 and wanted to upgrade to an LTS after 2.555.1. Fix: First upgrade Java on the controller and all agents to 21 (or straight to 25), verify on 2.541.3, then upgrade Jenkins. Limitation: An unsupported Java version will prevent the controller from starting, and an old Java on an agent will also cause connection failures.

Common errors and fixes

touch: cannot touch '/var/jenkins_home/copy_reference_file.log': Permission denied

Cause: A host directory is bind-mounted to JENKINS_HOME, but the directory owner is not UID 1000 (the jenkins user inside the container).

docker compose run --rm --entrypoint id jenkins
ls -ln /path/to/jenkins_home

Fix: Use a named volume (as this lesson does), or sudo chown -R 1000:1000 /path/to/jenkins_home.

An error occurred during installation: No such plugin: xxx / large-scale plugin installation failures in the wizard

Cause: The container cannot reach the Update Center (proxy, DNS, TLS interception).

docker compose exec jenkins curl -sI https://updates.jenkins.io/update-center.json | head -n 1
docker compose logs jenkins | grep -iE "updatecenter|SSLHandshake|UnknownHost" | tail

Fix: Configure a proxy (Manage Jenkins → Plugins → Advanced settings → HTTP Proxy); for enterprise TLS interception, import the root certificate into the JVM truststore; or in the wizard choose “Retry”, and failed plugins can be reinstalled on the Plugins page.

Running with Java 17 … which is older than the minimum required version (Java 21)

Cause: Starting Jenkins 2.555.1 or later on Java 17 (common with package installs or self-built images).

java -version
docker compose exec jenkins java -version

Fix: Install Java 21 or 25; for the container approach, directly use the -jdk21 / -jdk25 tag.

After rebuilding the container, it asks for initialAdminPassword again / all configuration is lost

Cause: JENKINS_HOME is not mounted to a volume (data lives in the container’s writable layer and is deleted with it), or you ran docker compose down -v.

docker volume ls | grep jenkins_home
docker inspect jenkins --format '{{range .Mounts}}{{.Name}} -> {{.Destination}}{{"\n"}}{{end}}'

Fix: Make sure jenkins_home:/var/jenkins_home; to restore from backup, after creating a new volume, tar xzf extract the backup back into it.

Command-line questions
1. Without logging in through the browser, confirm the version of the running Jenkins.
curl -sI http://localhost:8080/login | grep -i '^x-jenkins:'
# or: jcli version
2. Back up JENKINS_HOME to the current directory (excluding workspaces).
docker run --rm -v jenkinslab_jenkins_home:/src:ro -v "$PWD":/backup alpine:3.22 \
  tar czf /backup/jh.tgz -C /src --exclude=./workspace .
Scenario analysis question
The team wants to “always use the latest version” and writes in compose jenkins/jenkins:latest, and says “there are backups anyway.” How would you assess this?

latest is a weekly that changes every week and is unsuitable for production; even with LTS you should pin to a specific version (e.g. 2.580.2-jdk21). “Having backups” does not mean you can roll back: data formats migrate after an upgrade, so rolling back requires restoring the backup taken before the upgrade, and build records from the interim are lost. Recommendations: pin the LTS tag → subscribe to security advisories and the LTS changelog → verify on staging → back up → upgrade → smoke build.

Verified teaching videos

▶
Run Jenkins in Docker Container - Jenkins Pipeline Tutorial for Beginners 1/4 — TechWorld with Nana
English · Running Jenkins with Docker, volume mounts, the initial password and the setup wizard; recorded earlier, so for image tags follow this lesson's 2.580.2-jdk21

official documentation

Video storyboard script (about 75 seconds)

This lesson cannot directly generate a video or MP3, so a storyboard and narration script are provided instead.

Shot 1 · 0–15s
Visual: two timelines; the top one has a dot for each week (weekly), the bottom one a large dot every 12 weeks plus small patch dots (LTS).
Narration: production uses only LTS and pins to a specific version number.
Shot 2 · 15–40s
Visual: the terminal runs docker compose up and the log shows a 32-character password; the browser shows the Unlock page.
Narration: a brand-new data volume triggers the setup wizard, and the initial password is written to the secrets directory and the log.
Shot 3 · 40–60s
Visual: plugin installation progress bar, with ninety plugins turning green one by one.
Narration: 19 recommended plugins, about 90 including dependencies, all with versions chosen to be compatible with the current core version.
Shot 4 · 60–75s
Visual: the volume icon is packed into a tgz, with a lock beside it.
Narration: back up before upgrading; the backup contains keys, so store it encrypted.
or score ≥ 70% on the “Quiz”

Module 3 · Plugin system: installation, dependencies and the Update Center

13:00 – 21:00 · Almost all of Jenkins' capabilities come from plugins; installing them is not enough, you also need to control dependencies and versions and watch security advisories
8 minutesThe Update Center filters by core2.580.1 split out 9 plugins★★★★☆
Learning objectives
  • Understand what plugins are (extension points + .jpi packaging), dependency relationships requiredCore, and how the Update Center picks versions compatible with your core version.
  • Know the recommended plugins and the key plugins used in this course, with their current versions; know how Blue Ocean, Pipeline Stage View and Pipeline Graph View relate.
  • Be able to use the UI, the Jenkins CLI, and plugins.txt + jenkins-plugin-cli three methods to install and pin plugin versions.
  • Be able to handle security advisories, deprecated plugins, and load failures caused by missing dependencies.
Prerequisites: Module 2's jcli. Importance:★★★★☆

What: what a plugin is

A plugin is a .jpi (historically called .hpi) file, essentially a JAR with a manifest. It plugs into Jenkins through the core-defined extension points (extension point): new SCMs (Git), new build steps (sh,junit new credential types, new agent launch methods, new UI pages. Each plugin declares in its manifest:

  • Dependencies: required and optional dependencies with minimum versions, for example the Gitea plugin depends on git ≥ 5.10.1, credentials, scm-api, branch-api, and so on.
  • requiredCore: minimum core version, for example Gitea 286.v0740a_413c1eb_ requires 2.528.3, and Prometheus metrics 873.v054598e6e84d requires 2.555.3.

Plugin version numbers come in two styles: traditional 5.11.0 (Git plugin) and the automated-release style 1514.vb_01eb_014e7d4 (build number + Git commit hash, Credentials plugin); the latter has no semantic-versioning meaning and can only be compared by order.

Why: why dependencies and versions are the number-one operations problem

  • One recommended install brings in about 90 plugins, and each may have its own release cadence and security advisories.
  • Plugins have transitive dependencies: upgrading A may require upgrading B first, and B in turn requires a newer core.
  • Plugins run inside the controller's JVM, so a vulnerable plugin is a vulnerability in the controller. Most Jenkins security advisories concern plugins (for example, the 2026-09-16 and 2026-06-24 advisories involved only plugins).

How: how the Update Center picks versions

Jenkins requests https://updates.jenkins.io/update-center.json?version=<core version>, and the server returns trimmed for this core version metadata: for each plugin it gives only the latest version compatible with that core, plus its dependencies, checksums, security warnings and deprecation information. Using the 2026-11-16 data as an example:

PluginLatest version on plugins.jenkins.ioCore it requiresVersion the Update Center gives for 2.580.2
JUnit1463.v7508416a_349c (2026-11-15)2.589 (weekly)1458.1460.vd53b_087eeb_2c (requires 2.555.3)
Pipeline Graph View1134.v63b_71c6f549b_ (2026-11-16)2.5891053.v9df19e6ceed2 (requires 2.555.3)
Git5.11.02.504.35.11.0
Gitea286.v0740a_413c1eb_2.528.3286.v0740a_413c1eb_

This is why LTS users sometimes “cannot see the latest version” on the plugin page: the newest version needs a newer core, so the Update Center offers the highest compatible version you can use.

Key plugins used in this course (versions offered by the Update Center for 2.580.2, 2026-11-16)

Plugin (ID)VersionPurposeWhen to use
Pipeline (workflow-aggregator)608.v67378e9d3db_1Aggregate bundle: Pipeline engine, Declarative, shared libraries, input/milestone, etc.From Lesson 1 (recommended plugin)
Pipeline: Declarative (pipeline-model-definition)2.2293.v6e7193cec599Declarative syntax and validatorLessons 1 and 2
Pipeline: Groovy (workflow-cps)4403.v471713a_cea_19CPS execution engineLesson 2 covers the theory
Git (git)5.11.0Git SCM,checkout scmFrom Lesson 1
Credentials (credentials) / Credentials Binding (credentials-binding)1514.vb_01eb_014e7d4 / 728.v902a_273b_8947Credential storage / withCredentialsModule 6
JUnit (junit)1458.1460.vd53b_087eeb_2cTest reports, trends, UNSTABLEModule 7 (installed automatically as a dependency)
Pipeline Graph View (pipeline-graph-view)1053.v9df19e6ceed2New Pipeline stage view (recommended plugin)From Lesson 1
Gitea (gitea)286.v0740a_413c1eb_Gitea server, organization folders, webhooks, commit statusInstalled in this module, used in Lesson 2
Docker Pipeline (docker-workflow)653.v2f2c08eff0ecdocker.build(),agent { docker … }Installed in this module, used in Lesson 2
GitHub Branch Source1986.v801e40614d00GitHub multibranch and organizationRecommended plugin
Matrix Authorization Strategy (matrix-auth)3.3Matrix-based authorizationLesson 6
Configuration as Code (configuration-as-code)2147.v8a_8d38668c72JCasCLesson 5

Changes in 2.580.1: plugins split out of the WAR

Official upgrade guide: from 2.580.1 on 9 “detached plugins” are no longer bundled into jenkins.war (shrinking the WAR by more than 20 MB): bouncycastle API, Command Agent Launcher, Oracle Java SE Development Kit Installer, JAXB, Trilead API, SSH server, JavaBeans Activation Framework (JAF) API, JavaMail API, and Instance Identity. Instances that can reach the Update Center install them automatically when needed; offline instances must place these plugins manually before upgrading. In addition, very old instances upgrading directly from 1.577 or earlier must first install JUnit, Mailer, Matrix Authorization Strategy, Matrix Project and OWASP Markup Formatter.

When: plugin selection checklist

  • First check the plugins.jenkins.io listing for Health score, last release date, install count, unresolved security warnings, and whether it is marked deprecated or “up for adoption”.
  • If a Pipeline step plus a command-line tool can do the job, do not install another plugin for it (for example, directly sh 'docker build …').
  • UI-related: new instances use Pipeline Graph View (already in the recommended plugins); Blue Ocean still ships maintenance releases (1.27.26), but the project no longer develops new features for it, so new installs are not recommended.
Common misconceptions① “The newer the plugin, the better, so select all updates and upgrade”: a bulk upgrade can drag the whole dependency chain onto versions that need a newer core, so verify on a staging instance and pin versions before upgrading production. ② “Uninstalling a plugin removes it cleanly”: Job configurations that used the plugin still contain its XML, and the “Old data” administrative monitor will warn about it, so it needs to be cleaned up. ③ “Plugins only affect the Jobs that use them”: all plugins load in the same JVM, so a memory leak or startup failure in one plugin affects the entire controller.

Plugin architecture: extension points and dependencies

Jenkins core 2.580.2 (WAR): Queue, Node, Job model, security framework, Stapler Web, extension pointsSCM · Builder · Publisher · Step · CredentialsProvider · ComputerLauncher · ManagementLink … credentialsCredentialsProvider scm-api / git-clientSCMSource workflow-* (Pipeline)Step, FlowExecution docker-commonsDocker tooling and registry credentials gitea 286.v0740a_413c1eb_requiredCore 2.528.3 git 5.11.0requiredCore 2.504.3 docker-workflow 653.v2f2c08eff0ecrequiredCore 2.541.3
Figure 3-1: upper-layer plugins depend on lower-layer “API/library” plugins, and all of them ultimately work through core's extension points; all plugins share the controller's single JVM

Three installation paths

UI: Manage Jenkins → Plugins CLI: install-plugin … -deploy Image build: jenkins-plugin-cli Dependency resolution + downloadupdate-center.jsonSHA-256 verification JENKINS_HOME/plugins/Runtime installation: mutable, hard to reproduce /usr/share/jenkins/ref/plugins/Baked into the image: immutable, reproducible
Figure 3-2: use the UI/CLI for learning and emergencies; in production, pin versions in plugins.txt and bake them into the image (Lesson 5 combines this with JCasC)

Interactive: plugin dependency resolver (real metadata)

Data comes from the metadata the Update Center provided for core 2.580.2 on 2026-11-16. Tick the plugins you want to install and choose a core version; like the plugin manager, the resolver checks requiredCore → expands required dependencies → excludes parts already installed with the recommended plugins → lists the plugins that will be newly downloaded.

Tick plugins on the left…
$ jcli install-plugin …

Command table

CommandPurposeKey parameters
jcli install-plugin ID…Install from the Update Center (including dependencies)-deploy loads immediately; -restart restart after installing; you can also use ID:version
jcli list-plugins [ID]List installed plugins; if an update is available, the newer version appears in parentheses after the current version—
GET /pluginManager/api/json?depth=1Export the plugin list via RESTtree=plugins[shortName,version,active,hasUpdate]
jenkins-plugin-cliPlugin Installation Manager (built into the image)--plugin-file,--plugins,--list,--available-updates
jcli safe-restartwait for builds to finish, then restart (needed after uninstalling or downgrading)—

Install the Gitea and Docker Pipeline plugins

jcli install-plugin gitea docker-workflow -deploy
jcli list-plugins | grep -E '^(gitea|docker-workflow|docker-commons|authentication-tokens) '
Installing gitea from update center
Installing docker-workflow from update center
gitea                  Gitea                    286.v0740a_413c1eb_
docker-workflow        Docker Pipeline          653.v2f2c08eff0ec
docker-commons         Docker Commons           477.v289085a_b_6896
authentication-tokens  Authentication Tokens API 1.144.v5ff4a_5ec5c33

How to verify: Searchable under Manage Jenkins → Plugins → Installed; the “Gitea Organization” item appears when creating a new Item. Common errors:ERROR: Unable to find plugin—— wrong ID (use the short name, such as docker-workflow rather than “Docker Pipeline”). Production use: Emergency installs; routine production changes use plugins.txt.

Export a pinned plugins.txt

cd ~/jenkinslab
curl -s -u "admin:$(cat .secrets/jenkins-token)" \
  "http://localhost:8080/pluginManager/api/json?depth=1&tree=plugins[shortName,version]" \
  | python3 -c 'import sys,json; [print(f"{p[\"shortName\"]}:{p[\"version\"]}") for p in sorted(json.load(sys.stdin)["plugins"], key=lambda p:p["shortName"])]' \
  > plugins.txt
wc -l plugins.txt; grep -E '^(git|gitea|workflow-aggregator|junit):' plugins.txt
97 plugins.txt
git:5.11.0
gitea:286.v0740a_413c1eb_
junit:1458.1460.vd53b_087eeb_2c
workflow-aggregator:608.v67378e9d3db_1

(production approach) Bake plugins into the image

mkdir -p ~/jenkinslab/controller && cp ~/jenkinslab/plugins.txt ~/jenkinslab/controller/
cat > ~/jenkinslab/controller/Dockerfile <<'EOF'
FROM jenkins/jenkins:2.580.2-jdk21
COPY --chown=jenkins:jenkins plugins.txt /usr/share/jenkins/ref/plugins.txt
RUN jenkins-plugin-cli --plugin-file /usr/share/jenkins/ref/plugins.txt
EOF
docker build -t jenkinslab/controller:2.580.2-1 ~/jenkinslab/controller
# This lesson does not switch the compose image; Lesson 5 combines this with JCasC (-Djenkins.install.runSetupWizard=false)
When plugins in the image take effect The entrypoint script only copies ref/ plugins that do not yet exist in JENKINS_HOME into it; existing plugins are not overwritten (unless the file name ends with .override ). So “switching images downgrades plugins” does not necessarily hold for existing volumes; Lesson 5 covers the full procedure.

Goal: Install the Gitea and Docker Pipeline plugins, export plugins.txt, and review security and update notices. Environment: Module 2's jcli. Cost: None.

Check what the recommended plugins installed:
jcli list-plugins | wc -l
jcli list-plugins | grep -E '^(workflow-aggregator|git|credentials-binding|pipeline-graph-view|junit|timestamper|ws-cleanup) '

Note that JUnit is not among the 19 recommended plugins, but it is a transitive dependency of them, so it is already installed and the Module 7 junit steps can use it directly.

Install Gitea and Docker Pipeline: in the “Commands” tab, run the install-plugin. You can also do this in the UI: Manage Jenkins → Plugins → Available plugins → search for “Gitea” and “Docker Pipeline” → Install.
Verify the new features appear: the New Item page gains a new Gitea Organization; in Pipeline Syntax (the sidebar of any Pipeline Job) you can see the related docker global variable documentation.
Export plugins.txt: in the “Commands” tab, run the export command and save the output to ~/jenkinslab/plugins.txt. Lesson 5 uses it to build a controller image with pre-installed plugins.
Review updates and security notices: if Manage Jenkins shows a yellow or red notice at the top (administrative monitors), read each one; check updatable items under Plugins → Updates,but do not bulk-upgrade in this lesson, and keep versions consistent with the course.
Cleanup: keep the plugins; they are used in Lesson 2.

Case 1: a startup failure triggered by one “select all and update”

Problem: An administrator selected all 40 plugins on the Updates page, upgraded them, and restarted. The new version of one plugin required a higher version of a certain API plugin, but that API plugin's upgrade failed (download timed out). On startup Jenkins reported “Failed to load” and disabled a chain of plugins that depended on it, so no Pipeline could run. Action: Restored from backup plugins/; afterward the process changed to: verify on a staging instance → update plugins.txt → build a new image → roll out with a rolling replacement. Constraint: A staging instance that matches production is required.

Case 2: responding to a security advisory

Problem: A security advisory disclosed a CSRF / permission-check vulnerability in a plugin, and some plugins have no fix available yet. Action: Subscribe to the jenkinsci-advisories mailing list; Update Center warnings appear under Manage Jenkins; if a fix exists, upgrade; if none, evaluate disabling the plugin or using an alternative; for high-severity vulnerabilities, first restrict access at the reverse-proxy layer. Constraint: Deprecated plugins will not receive fixes, so the only option is to migrate.

Case 3: governing the number of plugins

Problem: Over the years, the instance accumulated 300+ plugins; startup takes 6 minutes and upgrades carry enormous risk. Action: Export the plugin list and usage (which Job configurations reference each plugin); disable plugins and observe for two weeks before uninstalling; new plugins require review (health score, maintainers, alternatives). Constraint: Plugins used indirectly through step names in a Pipeline are hard to spot in the configuration XML, so you need to scan the Jenkinsfile.

Common errors and fixes

Failed to load: Gitea (gitea 286.v0740a_413c1eb_) - Update required: Git (git 5.4.0) to be updated to 5.10.1 or higher

Cause: A dependency plugin's version is too old (common when .jpi files are placed manually offline, or when only the upper-layer plugin was upgraded).

jcli list-plugins git
docker compose logs jenkins | grep -A3 "Failed to load"

Fix: Upgrade the dependencies as prompted (jcli install-plugin git -deploy after jcli safe-restart); in offline environments, use jenkins-plugin-cli resolve the full dependency set on an internet-connected machine and then import it.

Failed to load: JUnit Plugin (junit 1463.v7508416a_349c) - Jenkins (2.589) or higher required

Cause: A latest version built for weekly was uploaded manually (for example, JUnit 1463.v7508416a_349c requires 2.589), while the current core is LTS 2.580.2.

Fix: Install through the Update Center (it offers a compatible version), or specify a compatible version in plugins.txt; or wait for an LTS release that includes that version.

No such DSL method 'docker' found among steps / No such DSL method 'junit'

Cause: The steps used in the Jenkinsfile come from plugins that are not installed or not enabled.

jcli list-plugins | grep -E '^(docker-workflow|junit) '

Fix: Install the corresponding plugin; “Pipeline Syntax → Steps Reference” shows the steps supported by the current instance.

Manage Jenkins shows “You have data stored in an older format and/or unreadable data”

Cause: After uninstalling a plugin, Job configurations still contain that plugin's data.

Fix: Manage Jenkins → Old Data (administrative monitor link): review it and then choose to discard it; or reinstall the plugin.

Command-line exercises
1. Install the Gitea plugin and load it immediately, without restarting.
jcli install-plugin gitea -deploy
2. Write a Dockerfile based on 2.580.2-jdk21 that pre-installs the plugins in plugins.txt.
FROM jenkins/jenkins:2.580.2-jdk21
COPY --chown=jenkins:jenkins plugins.txt /usr/share/jenkins/ref/plugins.txt
RUN jenkins-plugin-cli --plugin-file /usr/share/jenkins/ref/plugins.txt
Scenario analysis question
An offline data center's Jenkins 2.568.3 is to be upgraded to 2.580.2, but after the upgrade it fails to start and the log reports that instance-identity-related classes cannot be found. What is the cause and the correct approach?

Starting with 2.580.1, nine plugins including Instance Identity, bouncycastle API and JavaMail API are no longer bundled into the WAR; internet-connected instances install them automatically, but offline instances cannot find them. The correct approach: before upgrading, read the upgrade guide, and on an internet-connected machine use jenkins-plugin-cli to download these plugins and their dependencies, and place them in JENKINS_HOME/plugins/ then upgrade; or use a custom image with the plugins pre-installed. If it fails, roll back using the backup taken before the upgrade.

Verified teaching videos

▶
Learn Jenkins! Complete Jenkins Course - Zero to Hero — DevOps Journey
English · The course includes demonstrations of plugin installation and management; for plugin versions and the recommended list, follow this lesson

No verified video dedicated to “plugin dependencies, the Update Center and jenkins-plugin-cli” was found; please rely on the official documentation and the storyboard below.

official documentation

Video storyboard script (about 80 seconds)

This lesson cannot directly generate a video or MP3, so a storyboard and narration script are provided instead.

Shot 1 · 0–20s
Visual: core is a base board with block-like plugins plugged into it, with connecting lines between the blocks.
Narration: Jenkins' capabilities come from plugins; plugins attach to the core through extension points and also depend on one another.
Shot 2 · 20–45s
Visual: two versions of the JUnit plugin side by side; the latest one is labeled “requires 2.589”, and the other is labeled “offered for 2.580.2”.
Narration: the Update Center picks compatible versions based on your core version, so LTS users may not see the latest version.
Shot 3 · 45–65s
Visual: plugins.txt text scrolls, an arrow points to the Dockerfile, then to the image.
Narration: in production, write plugin versions into plugins.txt and bake them into the image to make the build reproducible.
Shot 4 · 65–80s
Visual: a red security advisory card pops up.
Narration: subscribe to security advisories; upgrade if a fix exists, and evaluate disabling the plugin if not.
or score ≥ 70% on the “Quiz”

Module 4 · Job types: Freestyle, Pipeline and Multibranch

21:00 – 28:00 · Choosing the right Job type determines where configuration lives, how it is reviewed, and how it scales to multiple branches
7 minutesPipeline as CodeFreestyle is included only for comparison★★★★☆
Learning objectives
  • Compare the use cases for Freestyle, Pipeline (inline script / from SCM), Multibranch Pipeline, Organization Folder and Folder.
  • Understand where Job configuration is stored jobs/<name>/config.xml, and be able to export and create Jobs with the CLI.
  • Understand Multibranch's “branch indexing” mechanism: each branch or PR that contains a Jenkinsfile automatically becomes a child Job.
  • Create credentials in the lab gitea-myapp and a Pipeline Job myapp (Pipeline script from SCM).
Prerequisites: Module 1's labels and executors. Importance:★★★★☆

What: main Job (Item) types

TypeWhere configuration livesTypical useLimitations
Freestyle projectJenkins UI (config.xml)Simple scripts, legacy tasksSteps are linear “build steps + post-build actions”; no stages, no parallelism, no reviewable code; hard to reuse
Pipeline (inline script)Groovy text box in the Job configurationTrying out syntaxThe script is not in version control; not recommended for long-term use
Pipeline (Pipeline script from SCM)The repository's Jenkinsfilesingle-branch CI (this lesson's myapp)Builds only the configured branch
Multibranch PipelineJenkinsfile in each branch / PRAll branches and PRs of one repositoryHands-on in Lesson 2
Organization Folder (Gitea / GitHub Organization)Scans all repositories in the organization that contain a JenkinsfileA platform team onboards dozens or hundreds of repositories at onceRequires the corresponding Branch Source plugin
FolderA container; does not run buildsOrganizes Jobs by team; holds folder-level credentials and permissions—
Multi-configuration (Matrix) projectUILegacy combinatorial matrix buildsFor new projects, use the Declarative matrix (Lesson 2)

Why: why Pipeline (Pipeline as Code) is the default choice

  • Reviewable, traceable: the Jenkinsfile goes through PRs alongside the code, so pipeline changes get the same history and review as code changes.
  • Resilient, expressive: stages, parallelism, conditions, retries, manual approval (input), and timeouts are all language features; a Pipeline can continue after a controller restart (Lesson 2).
  • Reusable: Shared Libraries extract common logic (Lesson 2).
  • Scales to branches: hand the same Jenkinsfile to Multibranch, and every branch and PR automatically gets CI.

How: what a Job looks like on disk

JENKINS_HOME/jobs/
├── hello-freestyle/
│   ├── config.xml                ← <project>: builders, publishers, assignedNode
│   ├── nextBuildNumber
│   └── builds/1/{build.xml,log}
└── myapp/
    ├── config.xml                ← <flow-definition>: CpsScmFlowDefinition + GitSCM + scriptPath
    └── builds/1/{build.xml,log,workflow/…}

The structure of Multibranch is jobs/myapp-mb/branches/main/…,branches/PR-1/…: child Jobs are automatically created and deleted by branch indexing,do not hand-edit a child Job's configuration, as the next indexing will overwrite it.

When: how to choose

SituationChoice
New project that needs CIMultibranch Pipeline (Lesson 2); first learn the syntax with a single-branch Pipeline (this lesson)
Platform team onboards an entire organizationOrganization Folder + Jenkinsfile convention + Shared Library
Ops scheduled scripts (backup, cleanup)Pipeline + triggers { cron('H 2 * * *') }
Many legacy Freestyle jobsMigrate gradually; to create Jobs in bulk, use Job DSL or JCasC (Lesson 5)
Common misconceptions① “When a Pipeline Job's Jenkinsfile changes, I have to sync it in Jenkins”: Pipeline script from SCM reads the Jenkinsfile from the repository on every build. ② “The Multibranch parent project can also have its own build steps”: the parent only discovers branches; all build logic comes from each branch's Jenkinsfile. ③ “Freestyle has been removed”: Freestyle is still part of core; it is just no longer recommended for new pipelines.

Where configuration comes from for the four Job types

FreestyleConfiguration: UI → config.xmlSteps: Execute shell …No version control Pipeline (from SCM)config.xml only stores “where to fetch”Logic: Jenkinsfile (main)One Job ↔ one branch MultibranchBranch source + discovery rulesOne child Job per branch / PRIndexing: scan or webhook Organization FolderScans all repositories in the organizationOne Multibranch per repositoryGitea / GitHub Org Gitea: lab/myapp main feature/health PR #1 lab/other repositories … Configured only in the SCM sectionOne repository URL
Figure 4-1: the further right, the more “code-like” and automated the configuration; this lesson covers the two on the left, and Lesson 2 covers Multibranch

Two checkouts in Pipeline script from SCM

controller① Lightweight checkout: fetch only the Jenkinsfile(lightweight checkout) gitea:3000lab/myapp.gitCredential gitea-myapp(user lab + token) agent1 workspace② Full checkout: checkout scm(runs automatically in Declarative) HTTP API / gitgit fetch
Figure 4-2: the controller first reads the Jenkinsfile to decide “what to do”, then the agent checks out the whole repository to do it; both sides must be able to reach Gitea and both use the credentials

Interactive: how different Job types react to the same code event

Choose a Job type and a Git event, and observe what Jenkins internally creates or triggers. The mechanism behind Multibranch is branch indexing: the branch source (SCMSource) lists all branches and PRs, creates a child Job for each head that contains a Jenkinsfile, and handles vanished heads according to the orphan strategy.

Ready.

Command table

CommandPurposeKey parameters
jcli list-jobs [folder]List Jobs—
jcli get-job NAME > config.xmlExport Job configurationInside a folder, use folder/job
jcli create-job NAME < config.xmlcreate a Job from XMLerrors if it already exists
jcli update-job NAME < config.xmloverwrite the configuration—
jcli build NAME -s -vtrigger a build, wait, and print the console log-s wait; -v print the log; -p k=v parameters
jcli console NAME [N]view the log of a specific build-f follow

Create the Pipeline Job myapp from XML

cd ~/jenkinslab
cat > myapp-job.xml <<'EOF'
<flow-definition plugin="workflow-job">
  <description>myapp CI (Lesson 1): Pipeline script from SCM</description>
  <keepDependencies>false</keepDependencies>
  <definition class="org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition" plugin="workflow-cps">
    <scm class="hudson.plugins.git.GitSCM" plugin="git">
      <configVersion>2</configVersion>
      <userRemoteConfigs>
        <hudson.plugins.git.UserRemoteConfig>
          <url>http://gitea:3000/lab/myapp.git</url>
          <credentialsId>gitea-myapp</credentialsId>
        </hudson.plugins.git.UserRemoteConfig>
      </userRemoteConfigs>
      <branches><hudson.plugins.git.BranchSpec><name>*/main</name></hudson.plugins.git.BranchSpec></branches>
    </scm>
    <scriptPath>Jenkinsfile</scriptPath>
    <lightweight>true</lightweight>
  </definition>
  <disabled>false</disabled>
</flow-definition>
EOF
jcli create-job myapp < myapp-job.xml
jcli list-jobs
hello-freestyle
myapp

How to verify: Open http://localhost:8080/job/myapp/configure, and the Pipeline section shows “Pipeline script from SCM”, the repository URL and the credentials. Common errors: If credentialsId in the XML points to a credential that does not exist, creation succeeds but the build fails with an authentication error. Production use: Put Job XML under version control for disaster recovery; for large-scale generation, use Job DSL / JCasC (Lesson 5).

Export and compare

jcli get-job hello-freestyle | head -n 20
<?xml version='1.1' encoding='UTF-8'?>
<project>
  <description>Comparison: Freestyle</description>
  <assignedNode>linux</assignedNode>
  <canRoam>false</canRoam>
  <builders>
    <hudson.tasks.Shell>
      <command>hostname; python3 --version</command>

Goal: Create a Freestyle Job as a comparison; create the credential gitea-myapp; create the Pipeline Job from XML myapp and observe the failure when “there is no Jenkinsfile yet”. Environment: agent1 is online, and the Gitea repository lab/myapp already has code. Cost: None.

Freestyle comparison: New Item → name hello-freestyle → Freestyle project → tick Restrict where this project can be run, set Label Expression to linux → add under Build Steps Execute shell: hostname; python3 --version → Save → Build Now. The console should display Building remotely on agent1 (linux docker) in workspace /home/jenkins/agent/workspace/hello-freestyle.
Create credential gitea-myapp (for the theory and more methods, see Module 6): Manage Jenkins → Credentials → System → Global credentials (unrestricted) → Add Credentials:
FieldValue
KindUsername with password
ScopeGlobal
Usernamelab
Password~/jenkinslab/.secrets/gitea-token content (Gitea access token, not lab's login password)
IDgitea-myapp (the same across the course; referenced by ID in the Jenkinsfile)
DescriptionGitea user lab token for lab/myapp
Create the Pipeline Job myapp: in the “Commands” tab, run the create-job (or in the UI: New Item → myapp → Pipeline → set Definition to Pipeline script from SCM → SCM: Git → Repository URL http://gitea:3000/lab/myapp.git → Credentials: select gitea-myapp → Branch */main → Script Path Jenkinsfile).
Build once and observe the failure: the repository does not have a Jenkinsfile yet.
jcli build myapp -s -v
Started from command line by admin
ERROR: Unable to find Jenkinsfile from git http://gitea:3000/lab/myapp.git
Finished: FAILURE

This failure proves the controller has already used the credential to access Gitea successfully (otherwise it would be an authentication error). Build again after Module 5 commits the Jenkinsfile.

Cleanup: hello-freestyle Can be deleted (jcli delete-job hello-freestyle), or kept for comparison. Keep myapp the Job and the credential.

Case 1: migrating 400 Freestyle Jobs

Problem: Over the years, Freestyle Jobs were copied and pasted between each other, so changing one shared step meant 400 separate edits. Action: First inventory (get-job export all XML for statistics), write the most common patterns as Shared Library steps, then migrate repository by repository to Multibranch + Jenkinsfile; during migration, old Jobs are disabled rather than deleted. Constraint: Some Freestyle plugins (certain post-build actions) have no Pipeline equivalent step and must be replaced.

Case 2: using folders for team isolation

Problem: All teams' Jobs sit flat in the root directory, and credentials are visible globally. Action: One Folder per team; team credentials are stored in folder-level credential stores, and permissions are granted on the folder (Lesson 6). Constraint: Moving a Job changes its URL, so bookmarks and external links need to be updated.

Case 3: automatic onboarding with an Organization Folder

Problem: Every new repository required asking the platform team to create a Job. Action: Use a GitHub / Gitea Organization Folder to scan the organization; any repository containing a Jenkinsfile is onboarded automatically, and webhooks trigger indexing. Constraint: Scan frequency must be balanced against API rate limits (especially noticeable with GitHub).

Common errors and fixes

ERROR: Unable to find Jenkinsfile from git http://gitea:3000/lab/myapp.git

Cause: The file is not on the branch, the Script Path has the wrong case (jenkinsfile), or the branch specifier is wrong (*/master).

git -C ~/jenkinslab/myapp ls-tree --name-only origin/main | grep -i jenkinsfile
jcli get-job myapp | grep -E "scriptPath|<name>"

Fix: Commit the Jenkinsfile to main, or correct the Script Path and branch.

stderr: fatal: unable to access 'http://localhost:3000/lab/myapp.git/': Failed to connect to localhost port 3000

Cause: A host address of localhost was used in Jenkins; inside the jenkins/agent1 containers, localhost points to the container itself.

docker compose exec jenkins curl -s -o /dev/null -w "%{http_code}\n" http://gitea:3000/api/v1/version

Fix: Change the repository URL to http://gitea:3000/lab/myapp.git.

stderr: remote: Unauthorized / fatal: Authentication failed for 'http://gitea:3000/lab/myapp.git/'

Cause: The Job did not select a credential (private repository), the credential's password field contains something other than a token or the token has been deleted, or the username is wrong.

curl -s -o /dev/null -w "%{http_code}\n" -u "lab:$(cat ~/jenkinslab/.secrets/gitea-token)" http://localhost:3000/api/v1/repos/lab/myapp

Fix: A 200 response means the token is valid, so check the credential ID the Job selects; a 401 response means regenerate the token and update the credential (Module 6).

Freestyle console: Building on the built-in node / stuck in queue

Cause:“Restrict where this project can be run” was not ticked. When the built-in node has 0 executors, the build waits indefinitely.

Fix: Fill in a label expression linux.

Command-line exercises
1. Export myapp's configuration to a file and find the credential ID it uses.
jcli get-job myapp > myapp-job.xml
grep credentialsId myapp-job.xml
2. Trigger myapp, wait for it to finish, and print the log.
jcli build myapp -s -v
Scenario analysis question
A team has 30 microservice repositories, each with main, several feature branches and PRs. Right now each service has one Freestyle Job that builds only main. How would you design the Jenkins Job structure?

Put a Jenkinsfile in each repository root and common logic in a Shared Library; in Jenkins, create an Organization Folder (GitHub/Gitea Organization) that scans the whole organization and automatically generates a Multibranch for each repository, so branches and PRs get CI automatically; create a folder per team to hold credentials and permissions; use webhooks to trigger indexing; disable the old Freestyle Jobs for a while, then delete them.

Verified teaching videos

▶
How to create Jenkins Pipeline with an Example | Pipeline as Code | Tech Primers — Tech Primers
English · Creating a Pipeline Job and Pipeline script from SCM; recorded earlier, so follow this lesson for the UI
▶
Jenkins Full Course in 4 Hours | Jenkins Tutorial For Beginners | DevOps Training | Edureka — edureka!
English · A long comprehensive course with demonstrations of creating Freestyle and Pipeline Jobs; you can jump to chapters

official documentation

Video storyboard script (about 70 seconds)

This lesson cannot directly generate a video or MP3, so a storyboard and narration script are provided instead.

Shot 1 · 0–20s
Visual: on the left, a Freestyle configuration form; on the right, Jenkinsfile code, with Git commit history beside the code.
Narration: Freestyle's configuration lives in Jenkins, while Pipeline logic lives in the repository, where it can be reviewed and traced back.
Shot 2 · 20–45s
Visual: one repository grows three branches and one PR, and Jenkins correspondingly grows four child Jobs.
Narration: a multibranch pipeline uses branch indexing to automatically create child jobs for each branch and PR that contains a Jenkinsfile.
Shot 3 · 45–70s
Visual: the controller fetches the Jenkinsfile first, then the agent checks out the whole repository.
Narration: the controller reads the Jenkinsfile first to decide what to do, then the agent checks out the code and does the work.
or score ≥ 70% on the “Quiz”

Module 5 · Your first Jenkinsfile: stage, step and post

28:00 – 35:00 · Write myapp's first pipeline in Declarative syntax: check out on agent1, run pytest, and handle the results with post
7 minutesPipeline: Declarative 2.2293post conditions run in a fixed order★★★★★
Learning objectives
  • Explain the difference between Declarative and Scripted Pipeline, and know why Declarative is the first choice for new projects.
  • Write out the complete structure of pipeline / agent / options / environment / stages / stage / steps / post .
  • Master the meaning and execution order of the post conditions (always, changed, fixed, regression, aborted, failure, success, unstable, unsuccessful, cleanup).
  • Be able to use declarative-linter to validate, try changes with Replay, generate snippets with Pipeline Syntax, and understand the difference between single and double quotes.
Prerequisites: Module 4's Job myapp. Importance:★★★★★

What: Jenkinsfile and the two syntaxes

DeclarativeScripted
Top levelpipeline { … }node { … }
StructureFixed sections and directives, syntax-checked before executionArbitrary Groovy code
Readability / barrier to entryHigh / lowDepends on the author / requires knowing Groovy
Built-in capabilitiesautomatic checkout,options,post,when,parallel,matrix, per-stage agent, Restart from Stageall have to be written by hand (try/catch/finally)
Escape hatchscript { … } Scripted code can be written inside the block—

Both syntaxes run on the same Pipeline engine (CPS). This course uses Declarative throughout, and complex logic goes into Shared Libraries (Lesson 2).

Why: why post and options exist

  • Builds without timeout can hang forever, permanently occupying an executor (the queue from Module 1 would get blocked).
  • Jobs without buildDiscarder will pile up all their build records in JENKINS_HOME, and the disk will eventually fill up.
  • post Gives “things that must run regardless of success or failure” (collecting test reports, cleaning up the workspace, sending notifications) a fixed place and order.

How: the order of a Declarative run

  1. The controller lightweight-checks out the Jenkinsfile → parses and validates the syntax (syntax errors fail here, without occupying an agent).
  2. Top level agent { label 'linux && docker' } → submits the queue task, allocates an executor on agent1, and locks the workspace (the lifecycle from Module 1).
  3. Automatic stages Declarative: Checkout SCM: runs in the workspace checkout scm (can be turned off with options { skipDefaultCheckout() } ).
  4. Runs each stage's steps in order; if a step fails (for example, if sh returns a non-zero exit code) → the build result is set to FAILURE, and subsequent stages are skipped.
  5. Post Declarative: Post Actions: conditions are evaluated in a fixed order —always → changed → fixed → regression → aborted → failure → success → unstable → unsuccessful → cleanup.
post conditionsWhen it runs
alwaysAlways runs
changedThis result differs from the previous one
fixedThis build succeeded, and the previous one failed or was unstable
regressionThis build failed, was unstable, or was aborted, and the previous one succeeded
abortedAborted (manually stopped or timed out)
failure / success / unstableResult is FAILURE / SUCCESS / UNSTABLE
unsuccessfulResult is not SUCCESS
cleanupRuns after all other conditions, regardless of result (suitable for cleanWs())

When: quick reference to common directives

DirectiveExampleDescription
agentagent { label 'linux && docker' },agent noneagent none when each stage declares its own agent
optionstimeout,timestamps(),buildDiscarder,disableConcurrentBuilds(),retry,skipDefaultCheckout()applies to the whole Pipeline (some can also be used at the stage level)
environmentAPP_NAME = 'myapp'becomes an environment variable; can also be used credentials('id') (Module 6)
parametersstring(name: 'TAG', defaultValue: '1.0')Parameterized builds (Lesson 2)
triggerscron('H 2 * * *'),pollSCM('H/5 * * * *'),upstreamcurrently provides three kinds: cron, pollSCM, upstream
whenwhen { branch 'main' }Conditionally run stages (Lesson 2)

Quotes: the easiest pitfall to hit

  • 'single quotes' are plain strings,$VAR passed to the shell as-is, and the shell expands environment variables.
  • “double quotes” is a Groovy GString,${env.BUILD_NUMBER} is replaced by Groovy on the controller. Using it for echo is convenient, but do not interpolate secrets into sh (Module 6).
  • '''triple single quotes''' Suits multi-line shell scripts.
Common misconceptions① “Just write Groovy anywhere in a stage”: in Declarative, steps only steps are allowed; variable assignments and loops must go into script { }. ② “The post success condition runs before always”: the order is fixed, with always first and cleanup last. ③ “Every sh runs in a new shell, so a venv activation persists”: on the contrary, each sh each step runs in a new process, so the command that activates the venv and the commands that use it must be written in the same sh step. ④ “If the Jenkinsfile is wrong, you can only commit again”: you can first edit and rerun it online with Replay, and commit once it is confirmed.

Jenkinsfile structure diagram

pipeline { agent { label 'linux && docker' } options { timeout · timestamps · discard } environment { APP_NAME = 'myapp' } stages { Declarative:Checkout SCM (automatic) stage('Info')steps { echo; sh } stage('Test')steps { sh '''…pytest''' } Added in Module 7Build · Smoke · Archive post { always → changed → fixed → regression → aborted → failure → success → unstable → unsuccessful → cleanup } Declarative: Post Actions (run after all Pipeline stages; a stage can also have its own post)
Figure 5-1: the Declarative skeleton is fixed: first declare “where and how to run”, then list the stages, and finally handle the results together.

Result state machine

Running SUCCESS UNSTABLE FAILURE / ABORTED All steps finish normally junit finds failed test cases / unstable steps (the result gets “worse” but execution continues) A step throws an error (sh non-zero, error) → subsequent stages are skipped; timeout / manual stop → ABORTED
Figure 5-2: results can only get “worse”, never “better”: once UNSTABLE, later successes do not bring the result back to SUCCESS

Jenkinsfile line-by-line executor

Choose an outcome and step through to see which line the engine reaches, what appears in the log, and which post blocks run (evaluated in the officially defined order). Assume the previous build was SUCCESS.

Evaluate post conditions
Ready.

Command table

Command / UIPurposeNotes
jcli declarative-linter < JenkinsfileValidate Declarative syntax on the controllerProvided by the Pipeline: Declarative plugin
POST /pipeline-model-converter/validateValidate via REST-F "jenkinsfile=<Jenkinsfile"
Job → Pipeline SyntaxSnippet Generator, Declarative Directive Generator, Global Variables ReferenceGenerated from the plugins installed on the current instance
Build → ReplayEdit the Jenkinsfile used for this build and rerun it, without committingRequires Run/Replay permission
Build → Restart from StageRestart from a stage (Declarative)Can be turned off with disableRestartFromStage() .

Your first Jenkinsfile

// ~/jenkinslab/myapp/Jenkinsfile (first version)
pipeline {
  agent { label 'linux && docker' }

  options {
    timestamps()
    timeout(time: 10, unit: 'MINUTES')
    buildDiscarder(logRotator(numToKeepStr: '20'))
  }

  environment {
    APP_NAME = 'myapp'
  }

  stages {
    stage('Info') {
      steps {
        echo "Building ${env.APP_NAME} #${env.BUILD_NUMBER} on ${env.NODE_NAME}"
        sh 'git log -1 --oneline && python3 --version'
      }
    }
    stage('Test') {
      steps {
        sh '''
          python3 -m venv .venv
          . .venv/bin/activate
          pip install --quiet -r requirements-dev.txt
          python -m pytest -q
        '''
      }
    }
  }

  post {
    always  { echo "Result: ${currentBuild.currentResult}" }
    success { echo 'Tests passed' }
    failure { echo 'Something failed - check the console log' }
  }
}

Validate, commit, build

cd ~/jenkinslab/myapp
jcli declarative-linter < Jenkinsfile
git add Jenkinsfile && git commit -m "ci: first Jenkinsfile"
AUTH=$(printf 'lab:%s' "$(cat ../.secrets/gitea-token)" | base64 | tr -d '\n')
git -c http.extraHeader="Authorization: Basic $AUTH" push
jcli build myapp -s -v
Jenkinsfile successfully validated.
Started from command line by admin
Obtained Jenkinsfile from git http://gitea:3000/lab/myapp.git
[Pipeline] Start of Pipeline
[Pipeline] node
Running on agent1 in /home/jenkins/agent/workspace/myapp
[Pipeline] { (Declarative: Checkout SCM)
[Pipeline] checkout
using credential gitea-myapp
 > git fetch --tags --force --progress -- http://gitea:3000/lab/myapp.git +refs/heads/*:refs/remotes/origin/*
Checking out Revision 5c7e2a1… (refs/remotes/origin/main)
[Pipeline] { (Info)
[Pipeline] echo
10:21:07  Building myapp #2 on agent1
[Pipeline] sh
10:21:07  + git log -1 --oneline
10:21:07  5c7e2a1 ci: first Jenkinsfile
10:21:07  + python3 --version
10:21:07  Python 3.13.5
[Pipeline] { (Test)
[Pipeline] sh
10:21:15  ..                                                     [100%]
10:21:15  2 passed in 0.21s
[Pipeline] { (Declarative: Post Actions)
[Pipeline] echo
10:21:15  Result: SUCCESS
[Pipeline] echo
10:21:15  Tests passed
[Pipeline] End of Pipeline
Finished: SUCCESS

How to verify: The Job page shows a Pipeline Graph with two stages (Info, Test); build #2 is green. Common errors:WorkflowScript: 3: Invalid agent type … Syntax errors and similar mistakes are reported immediately by the linter and at the start of the build. Production use: Run the linter first in PR checks to avoid merging syntax errors into main.

Goal: Commit the first Jenkinsfile and get a green build; try out Replay, post conditions and timeout. Environment: Module 4's Job myapp, credentials gitea-myapp. Cost: None.

Write and validate: save the Jenkinsfile from the “Commands” tab as ~/jenkinslab/myapp/Jenkinsfile, then run jcli declarative-linter < Jenkinsfile, which should print Jenkinsfile successfully validated.
Commit, push, build: following the “Commands” tab, run it and get Finished: SUCCESS. In the browser, open the build → view the Pipeline Graph (provided by the recommended Pipeline Graph View plugin), and click each stage to view its log.
Try a failure with Replay: on the build page → Replay → change python -m pytest -q to python -m pytest -q && exit 1 → Run. Observe: the Test stage turns red, post runs always and failure; result FAILURE. Replay does not modify the repository.
Run a normal build again: jcli build myapp -s. This time the previous build was FAILURE and this one is SUCCESS; if you add fixed { echo 'fixed!' } (try it with Replay), it will run.
Try the timeout: with Replay, change timeout to timeout(time: 20, unit: 'SECONDS'), and in Test add sleep 60, and observe Timeout has been exceeded as well as the ABORTED result; the post block for aborted runs.
Cleanup: no cleanup needed; the Jenkinsfile stays on main, and Module 7 extends it.

Case 1: a forgotten hung build

Problem: An integration test occasionally hung with no timeout set; over the weekend all executors were occupied, and on Monday every build was queued. Action: Add uniformly through the Shared Library template options { timeout(time: 30, unit: 'MINUTES') }, and add a shorter timeout at the stage level for steps that tend to hang. Constraint: A timeout aborts the Pipeline step; child processes started by sh are usually killed, but background processes that leave the process group (for example nohup) may linger on the agent.

Case 2: disk filled up with build records

Problem: The controller disk is 95% full, mostly with years of build logs and artifacts. Action: Standardize all Jenkinsfiles on buildDiscarder(logRotator(numToKeepStr: '20', artifactNumToKeepStr: '5')); also add a default build discard policy at the global level. Constraint: Builds that audit requires to be kept must use “Keep this build forever” or external archiving.

Case 3: collecting results with post

Problem: Test reports were not published when tests failed, because junit was written after sh, and it no longer runs once sh fails. Action: Move junit into the stage's post { always { … } } (the Module 7 approach). Constraint: junit errors when the report file does not exist; add allowEmptyResults: true.

Common errors and fixes

WorkflowScript: 12: Expected a step @ line 12, column 9.

Cause: Groovy statements were written directly inside steps (for example def x = 1,if).

Fix: Move into script { … }, or use when,environment etc. directives. First use jcli declarative-linter < Jenkinsfile to validate locally.

.venv/bin/activate: No such file / pip: command not found (in the second sh step)

Cause: Each sh is a separate process, and the activate from the previous sh is not preserved; or the agent image does not have python3-venv.

Fix: Write activation and use in the same sh '''…''' step, or directly use .venv/bin/python -m pytest; confirm the agent image installs python3-venv (the Dockerfile from Module 0).

groovy.lang.MissingPropertyException: No such property: BUILD_NUMBER for class: groovy.lang.Binding

Cause: Wrote ${BUILD_NUMBER} in a Groovy string, but in an unsupported context, or misspelled.

Fix: In Groovy, use ${env.BUILD_NUMBER}; in shell, use single quotes around 'echo $BUILD_NUMBER' so the shell expands it. For the list of global variables, see Pipeline Syntax → Global Variables Reference.

Timeout has been exceeded … Finished: ABORTED

Cause: The build exceeded options { timeout(…) }.

Fix: Find the slow step (timestamped log) and fix the root cause of the hang; only raise the timeout if it is truly necessary.

Command-line exercises
1. Without committing any code, validate the Jenkinsfile syntax on the controller.
jcli declarative-linter < Jenkinsfile
2. Write a post block: print the result regardless of outcome; print fixed only when “recovering from a failure”; finally, clean up the workspace.
post {
  always  { echo "Result: ${currentBuild.currentResult}" }
  fixed   { echo 'fixed!' }
  cleanup { cleanWs() }
}
Scenario analysis question
A colleague's Jenkinsfile puts junit 'reports/*.xml' in the same steps block after sh in the Test stage, and when tests fail, Jenkins shows no failed-test details. Why, and how should it be fixed?

sh returns non-zero because pytest failed, which throws an error, so the later junit in the same steps block no longer runs. Change it by adding, in the Test stage, post { always { junit 'reports/junit.xml' } }, and have pytest generate JUnit XML (--junitxml); going further, you can mark test failures as UNSTABLE instead of FAILURE (Module 7).

Verified teaching videos

▶
Complete Jenkins Pipeline Tutorial | Jenkinsfile explained — TechWorld with Nana
English · Jenkinsfile structure, Scripted vs Declarative, post, environment variables, when, and more; closely matches this module
▶
How to create Jenkins Pipeline with an Example | Pipeline as Code | Tech Primers — Tech Primers
English · Writing a Jenkinsfile from scratch and running it

official documentation

Video storyboard script (about 80 seconds)

This lesson cannot directly generate a video or MP3, so a storyboard and narration script are provided instead.

Shot 1 · 0–20s
Visual: the Jenkinsfile skeleton appears block by block: agent, options, environment, stages, post.
Narration: a Declarative pipeline has a fixed skeleton: first say where and how to run, then list the stages, and finally handle the results.
Shot 2 · 20–45s
Visual: a highlighted cursor moves down line by line, while the log on the right scrolls in sync.
Narration: the engine first checks out the code automatically, then runs each stage in turn; each sh is a separate process.
Shot 3 · 45–65s
Visual: the ten post conditions are lined up in a column, with always, failure, unsuccessful and cleanup lit up.
Narration: post conditions are evaluated in a fixed order, with always first and cleanup last.
Shot 4 · 65–80s
Visual: the terminal runs declarative-linter and shows successfully validated.
Narration: validate before committing, saving a build that would otherwise fail.
or score ≥ 70% on the “Quiz”

Module 6 · Credentials and security basics

35:00 – 42:00 · Where the gitea-myapp credential lives, how it is encrypted, who can use it, and how to hand it safely to build steps
7 minutesCredentials 1514 · Binding 728Masking is not a security boundary★★★★★
Learning objectives
  • Recognize common credential types, credential stores (system / folder / user) and scopes (Global vs System).
  • Know how credentials are encrypted at rest (credentials.xml + secrets/) and what administrator privileges mean.
  • Be able to use credentials in a Pipeline in three ways: the SCM's credentialsId,environment { X = credentials('id') },withCredentials.
  • Understand the principle and limits of log masking, and avoid the warning "A secret was passed to \"sh\" using Groovy String interpolation"; master the most basic security settings.
Prerequisites: The gitea-myapp Job created in Module 4. Importance:★★★★★

What: credential types

KindContentsPipeline bindingUse in this course
Username with passwordUsername + password/tokenusernamePassword; credentials() generates X, X_USR, X_PSWgitea-myapp (lab + Gitea token),registry-creds (Lessons 3, 4)
Secret textSingle string (API token)stringWebhook secret, Slack token
Secret fileWhole file (kubeconfig)file (bound as a temporary file path)Lesson 5
SSH Username with private keyUsername + private key (+ passphrase)sshUserPrivateKeySSH clone, SSH agent
CertificatePKCS#12 certificatecertificateClient certificate authentication
Types provided by pluginsGitHub App, Azure, AWS, Kubernetes service accounts, etc.Steps from each pluginLessons 3–5

Stores, domains and scopes

  • Stores: system level (Manage Jenkins → Credentials → System),folder level (visible only to Jobs inside that folder; the preferred choice for team isolation), and user level (usable only for operations that user triggers).
  • Domain: a hint that groups credentials by hostname or protocol; the default is “Global credentials (unrestricted)”.
  • Scope: GLOBAL—— usable by both Jobs and Jenkins itself; SYSTEM—— for Jenkins' own use only (for example, the controller connecting to agents over SSH, or sending email),builds cannot read it.

How: encrypted storage and decryption

System-level credentials are stored in JENKINS_HOME/credentials.xml, and the password field is ciphertext like {AQAAABAAAA…} . The encryption key secrets/hudson.util.Secret is itself further secrets/master.key encrypted. Conclusion:

  • Anyone who gets the entire JENKINS_HOME (including secrets/) can decrypt all credentials; backups must be stored encrypted (Module 2).
  • Anyone with Overall/Administer can read any credential through the script console; keep administrators few and precise (Lesson 6).
  • Anyone who can modify a Jenkinsfile and run it on a Job that can use the credential can use the credential in a build; so keep credentials in the narrowest possible folder and give tokens minimum permissions.

Three ways to use credentials

MethodExampleBest for
credentialsId configured in SCMJob configuration or git url: …, credentialsId: 'gitea-myapp'fetching code
environment + credentials()GITEA = credentials('gitea-myapp') → $GITEA_USR,$GITEA_PSWwhen the whole Pipeline or a specific stage needs it
withCredentialswithCredentials([usernamePassword(credentialsId: 'gitea-myapp', usernameVariable: 'U', passwordVariable: 'P')]) { sh '…' }Recommended: smallest scope; exists only within the block

Log masking: principle and limits

After binding credentials, the Credentials Binding plugin registers these values with the build's log filter, and when the plaintext appears in the log it is replaced with ****. However, it only recognizes the “plaintext”: if a script base64-encodes the token, reverses it, prints it character by character, or writes it to an artifact file, masking cannot stop it. Masking prevents accidental printing, not malicious access.

Why you must not interpolate secrets with double quotes

// ✗ Unsafe: Groovy first substitutes the value of $GITEA_PSW into the command string,
//   the plaintext ends up in sh's arguments (visible to ps) and in Pipeline's internal records
sh "curl -u lab:${GITEA_PSW} http://gitea:3000/api/v1/user"
// ✓ Safe: single quotes; the value is passed to the shell only as an environment variable, which the shell expands
sh 'curl -u "lab:$GITEA_PSW" http://gitea:3000/api/v1/user'

Jenkins prints an explicit warning in the log: Warning: A secret was passed to "sh" using Groovy String interpolation, which is insecure.

Post-setup security baseline (covered in depth in Lesson 6)

SettingState after setup wizardRecommendation for this lesson
Security RealmJenkins built-in user databaseKeep for the lab; in production, connect SSO (Lesson 6)
AuthorizationLogged-in users can do anything; anonymous users cannot readKeep for the lab; in production, switch to matrix or role-based authorization
CSRF protectionEnabled (crumb)Keep; scripts use API tokens
Agent → Controller access controlAlways enabled (since 2.326)Keep
Built-in node executorsDefault 2Set to 0 (already done in Module 1)
Network exposure—Bind only to 127.0.0.1 (done in compose); in production, place it behind a TLS reverse proxy
Common misconceptions① “If the log shows **** we are safe”: masking only filters the plaintext. ② “Setting credentials to SYSTEM is safer, so set them all to SYSTEM”: builds cannot use SYSTEM credentials, and SCM checkout will not find them either. ③ “Using lab's login password as the credential is just as good”: a token can be scoped and revoked separately, while a leaked password means the account is taken over. ④ “Putting credentials in the global store is the least effort”: any Job can reference global credentials, so for team setups use folder-level credentials.

Credentials from storage to build steps

controller secrets/master.key→ hudson.util.Secret(decryption key) credentials.xmlid=gitea-myapppassword={AQAAAB…} CredentialsProvider.lookup Look up by ID within the visible scope: folder → system (GLOBAL) SYSTEM scope is not visible to builds Decrypt → register with the log masking filter agent1 (the process where the sh step runs) Environment variable GITEA_USER=labGITEA_TOKEN= (plaintext, only inside the block) sh 'curl -u "$GITEA_USER:$GITEA_TOKEN" …' Output streams back to the controllerPlaintext in the log → **** remoting
Figure 6-1: the credential is decrypted on the controller and handed to the process on the agent as an environment variable via remoting; the log is masked when it returns to the controller

Scopes and visibility

Jenkins (system store) GLOBAL: gitea-myappUsable by all JobsAlso usable by Jenkins itself SYSTEM: agent-ssh-keyFor Jenkins itself only(connecting agents, sending email) Folder team-a (folder store)team-a-deploy-tokenUsable only by Jobs under team-a/*When IDs clash, the nearer one (folder) takes precedence
Figure 6-2: the narrower a credential's scope, the smaller the exposure: team credentials go in the folder, and credentials Jenkins uses internally are set to SYSTEM

Animation: resolution, binding and masking of a single withCredentials call

Choose a form and observe how the Credentials Binding plugin looks up the credential, hands the value to the agent, and what appears in the log.

Ready.

Command table

CommandPurposeNotes
jcli list-credentials system::system::jenkinsList credentials in the system store (does not display secrets)CLI provided by the Credentials plugin
jcli create-credentials-by-xml system::system::jenkins _ < cred.xmlCreate the credential via XML (_ the global domain)the XML holds it in plaintext, so delete the file after use
jcli update-credentials-by-xml system::system::jenkins _ ID < cred.xmlRotate (update) the credentialthe ID stays the same, so jobs need no changes
jcli delete-credentials system::system::jenkins _ IDDelete the credential—

Create / rotate gitea-myapp via XML

cd ~/jenkinslab
umask 077
cat > /tmp/gitea-myapp.xml <<EOF
<com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl>
  <scope>GLOBAL</scope>
  <id>gitea-myapp</id>
  <description>Gitea user lab token for lab/myapp</description>
  <username>lab</username>
  <password>$(cat .secrets/gitea-token)</password>
</com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl>
EOF
# Created in the UI in Module 4: use update; on a fresh environment, use create
jcli update-credentials-by-xml system::system::jenkins _ gitea-myapp < /tmp/gitea-myapp.xml \
  || jcli create-credentials-by-xml system::system::jenkins _ < /tmp/gitea-myapp.xml
shred -u /tmp/gitea-myapp.xml 2>/dev/null || rm -f /tmp/gitea-myapp.xml
jcli list-credentials system::system::jenkins
===========================================================
Domain           (global)
Description
# of Credentials 1
===========================================================
Id               Name
================ ==========================================
gitea-myapp      lab/****** (Gitea user lab token for lab/myapp)
===========================================================

How to verify: It appears under Manage Jenkins → Credentials gitea-myapp, where the password field shows only “Concealed” once opened. Common mistake: The XML heredoc uses the 'EOF' (quoted) delimiter, which causes $(cat …) the variables not to be expanded, so the literal text gets stored. Production use: Token rotation script: generate a new token → update → smoke build → revoke the old token.

Using it in a Pipeline (recommended)

stage('Gitea API') {
  steps {
    withCredentials([usernamePassword(credentialsId: 'gitea-myapp',
                                      usernameVariable: 'GITEA_USER',
                                      passwordVariable: 'GITEA_TOKEN')]) {
      sh '''
        curl -sf -u "$GITEA_USER:$GITEA_TOKEN" http://gitea:3000/api/v1/repos/lab/myapp \
          | python3 -c 'import sys,json; d=json.load(sys.stdin); print(d["full_name"], "private =", d["private"])'
        echo "token is $GITEA_TOKEN"     # Masking demo: the log shows ****
      '''
    }
  }
}
[Pipeline] withCredentials
Masking supported pattern matches of $GITEA_TOKEN
[Pipeline] {
[Pipeline] sh
+ curl -sf -u lab:**** http://gitea:3000/api/v1/repos/lab/myapp
lab/myapp private = True
+ echo token is ****
token is ****
[Pipeline] }

Whether the username is also masked depends on the “Treat username as secret” option on the credential; when it is checked, every raw occurrence of “lab” in the log becomes **** (including lab/myapp), so you usually do not need to check it.

Goal: Confirm gitea-myapp, using an inline Pipeline job to demonstrate withCredentials, masking and interpolation warnings, and finally complete one token rotation. Environment: Modules 0–5. Cost: None.

Review credentials and encrypted storage:
jcli list-credentials system::system::jenkins
docker compose exec jenkins grep -A1 "<password>" /var/jenkins_home/credentials.xml | head -n 2
          <password>{AQAAABAAAAAwq8c…kM=}</password>
Create the demo job cred-demo (inline Pipeline; the script runs in the sandbox):
cat > ~/jenkinslab/cred-demo.xml <<'EOF'
<flow-definition plugin="workflow-job">
  <description>Module 6: credential binding, masking and interpolation warning demo</description>
  <definition class="org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition" plugin="workflow-cps">
    <script>pipeline {
  agent { label 'linux' }
  options { skipDefaultCheckout() }
  stages {
    stage('safe') {
      steps {
        withCredentials([usernamePassword(credentialsId: 'gitea-myapp', usernameVariable: 'GITEA_USER', passwordVariable: 'GITEA_TOKEN')]) {
          sh 'curl -sf -o /dev/null -w "repo api: %{http_code}\\n" -u "$GITEA_USER:$GITEA_TOKEN" http://gitea:3000/api/v1/repos/lab/myapp'
          sh 'echo "token is $GITEA_TOKEN"'
        }
      }
    }
    stage('unsafe-demo') {
      environment { GITEA = credentials('gitea-myapp') }
      steps {
        sh "echo interpolated ${GITEA_PSW}"
      }
    }
  }
}</script>
    <sandbox>true</sandbox>
  </definition>
</flow-definition>
EOF
jcli create-job cred-demo < ~/jenkinslab/cred-demo.xml
jcli build cred-demo -s -v | grep -E "repo api|token is|interpolated|Warning|Affected"
repo api: 200
token is ****
Warning: A secret was passed to "sh" using Groovy String interpolation, which is insecure.
		 Affected argument(s) used the following variable(s): [GITEA_PSW]
interpolated ****

The second stage's output is masked as well, but the warning tells you that the secret has already been passed in plaintext as a command-line argument (on the agent, it can be seen with ps ), and that is the real problem.

Rotate the token: generate a new token in Gitea → update the credential → verify → delete the old token.
cd ~/jenkinslab
docker compose exec -T -u git gitea gitea admin user generate-access-token \
  --username lab --token-name jenkins-myapp-$(date +%Y%m%d) --scopes write:repository \
  | awk '{print $NF}' > .secrets/gitea-token
# Run update-credentials-by-xml from the “Commands” tab, then:
jcli build cred-demo -s -v | grep "repo api"
# Old token: Gitea web UI → top-right lab → Settings → Applications → delete the token named jenkins-myapp
Cleanup: jcli delete-job cred-demo; keep gitea-myapp (used by Module 7 and Lesson 2).

Case 1: log masking bypassed

Problem: A build script ran env | base64, and the log contained a string that could be decoded into a cloud key, so masking did not work. Fix: Revoke and rotate the key; the Shared Library must not print the full environment; PR builds from external contributors get no credentials at all (the trust policy from Lesson 2 Multibranch). Limitation: Anyone who can modify the Jenkinsfile and use a credential can effectively obtain it, so rely on folder isolation, least privilege and short-lived tokens.

Case 2: a global credential misused by another team

Problem: Team A's deployment token was stored globally; Team B copied a Jenkinsfile that referenced the same ID directly, so the deployment went to Team A's environment. Fix: Migrate to folder-level credentials, combined with folder permissions (Lesson 6). Limitation: During migration, a folder credential with the same ID takes precedence over the global one, so verify in batches.

Case 3: moving from long-lived keys to short-lived identities

Problem: Jenkins holds many long-lived access keys for cloud accounts. Fix: Lessons 3 and 4 switch to managed identities / workload identities and similar approaches, so Jenkins avoids storing long-lived cloud keys where possible. Limitation: Whether it can be fully keyless depends on where the agent runs and on plugin support; Lessons 3 and 4 verify this item by item.

Common errors and fixes

ERROR: Could not find credentials entry with ID 'gitea_myapp'

Cause: wrong ID (underscore / hyphen), the credential is in another folder, or its scope is SYSTEM.

jcli list-credentials system::system::jenkins

Fix: Use consistently gitea-myapp; set the scope of credentials used by builds to Global.

Warning: A secret was passed to "sh" using Groovy String interpolation, which is insecure.

Cause: A double-quoted string uses ${…} to insert the credential variable.

Fix: Switch to single quotes so the shell expands the environment variable: sh 'curl -u "$GITEA_USER:$GITEA_TOKEN" …'.

curl: (22) The requested URL returned error: 401 (calling the Gitea API inside a withCredentials block)

Cause: the token was deleted or expired, or its scope is insufficient (for example, it only has read:user).

curl -s -o /dev/null -w "%{http_code}\n" -H "Authorization: token $(cat ~/jenkinslab/.secrets/gitea-token)" http://localhost:3000/api/v1/repos/lab/myapp

Fix: Generate a new token with the write:repository scope and update the credential.

After restoring credentials.xml, all credentials show as empty / decryption fails

Cause: Only credentials.xml was restored, without restoring secrets/master.key and secrets/hudson.util.Secret.

Fix: Restore the full JENKINS_HOME backup (including secrets/), or re-enter the credentials.

Command-line task
1. List all credential IDs in the system store.
jcli list-credentials system::system::jenkins
2. Write a Pipeline snippet that calls the Gitea API securely using gitea-myapp.
withCredentials([usernamePassword(credentialsId: 'gitea-myapp', usernameVariable: 'U', passwordVariable: 'T')]) {
  sh 'curl -sf -u "$U:$T" http://gitea:3000/api/v1/repos/lab/myapp'
}
Scenario analysis
Security audit finding: all teams share one Jenkins, all credentials are in the global domain with Global scope, and many are long-lived personal passwords. Give the remediation order.

① Inventory the credentials and the jobs that reference them; ② replace all personal passwords with scoped tokens for a service account, and set up expiry and a rotation process; ③ create a folder per team and migrate team credentials to folder-level storage, combined with folder permissions; ④ credentials used only by Jenkins itself are set to SYSTEM; ⑤ check interpolation in Jenkinsfiles (warnings in logs) and switch to single quotes; ⑥ gradually move cloud credentials to managed / workload identities (Lessons 3 and 4); ⑦ limit the number of administrators and encrypt backups.

Verified instructional videos

No verified video focused on “Jenkins credential scope, encrypted storage and interpolation warnings” was found. The videos below include segments on credential usage and serve as supplementary material:

▶
Complete Jenkins Pipeline Tutorial | Jenkinsfile explained — TechWorld with Nana
English · Jenkinsfile walkthrough, including the section on using credentials in a Pipeline (based on the video's actual content)

Official documentation

Video storyboard script (about 90 seconds)

This courseware cannot directly generate video or MP3, so a storyboard and narration script are provided instead.

Shot 1 · 0–20s
Visual: a safe labeled credentials.xml, with a key labeled master.key hanging beside it.
Narration: credentials are encrypted on the controller, and the key is also on the controller, so backups and administrator rights must be strictly protected.
Shot 2 · 20–45s
Visual: a withCredentials block opens, and an envelope flies from the controller to the agent, becoming environment variables.
Narration: withCredentials passes the secret to processes on the agent as environment variables, only inside the block.
Shot 3 · 45–70s
Visual: the token in the log is starred out; another line with a base64 string is not masked, and a red box flashes.
Narration: log masking only matches the raw text, so changing the encoding gets past it. It guards against accidental printing, not malicious actors.
Shot 4 · 70–90s
Visual: double-quoted code is crossed out and replaced with single quotes.
Narration: do not interpolate secrets with double quotes; let the shell expand the environment variables itself.
or score ≥ 70% on the “Quiz”

Module 7 · Build myapp: testing, packaging and archiving

42:00 – 50:00 · The complete first CI: pytest + JUnit report → docker build to myapp:1.0 → smoke test /healthz → archive the report and record the fingerprint
8 minutesJUnit 1458 · Docker 29the image is on the host's dockerd★★★★★
Learning goals
  • Pass pytest results to Jenkins as JUnit XML, and understand the difference between FAILURE and UNSTABLE when tests fail and how to choose between them.
  • Build and tag the image on agent1 myapp:1.0 and myapp:<build number>, and write OCI labels that record the commit.
  • Run a smoke test with an in-container health check, and make sure the container is cleaned up even on failure.
  • Use archiveArtifacts + fingerprint to save build information, so you know where the artifacts live on the controller and why the image itself should not be archived.
Prerequisites: The Jenkinsfile from Module 5, and image building from the Docker course. Importance:★★★★★

What: what this CI does

StageWhat it doesOutputOn failure
Declarative: Checkout SCMCheck out main using gitea-myappworkspace,GIT_COMMIT and similar environment variablesFAILURE (authentication, network)
Testvenv + pytest, generating reports/junit.xmla test report (the Test Result page and trend graph in Jenkins)FAILURE; later stages are skipped, but the report is still recorded
Build imagedocker build, tagged myapp:1.0 and myapp:$BUILD_NUMBERthe image in the host's dockerdFAILURE
Smoke testRun the container and request /healthz—FAILURE, and print the container logs
ArchiveWrite reports/build-info.json, archive reports/** and record the fingerprintartifacts on the controllerFAILURE

Why: FAILURE or UNSTABLE

Jenkins convention: FAILURE means the build process itself failed (compile errors, step errors); UNSTABLE means the build completed but quality falls short (typically test failures). junit The step sets the result to UNSTABLE when it finds failing test cases. This lesson's choice:

  • When pytest fails, make sh return a non-zero exit code → FAILURE, so the later Build image stage does not run —no image is built for code that fails its tests.
  • junit Put the post { always { … } }, so even when it fails, the failing cases still appear on the Test Result page.
  • If the team wants test failures to show as yellow UNSTABLE and skip later stages, they can use catchError(buildResult: 'UNSTABLE', stageResult: 'UNSTABLE') { sh '…pytest…' } Pair with options { skipStagesAfterUnstable() }. Both approaches are reasonable; what matters is that the whole team is consistent.

How: where artifacts and fingerprints are stored

  • archiveArtifacts Copy the files in the agent workspace to the controller: JENKINS_HOME/jobs/myapp/builds/N/archive/. So only small files (reports, metadata, binary packages) should be archived,do not archive image tars or large files— images should be pushed to an image registry (Lessons 3 and 4).
  • fingerprint: true Compute an MD5 for each file and record it in JENKINS_HOME/fingerprints/, so you can trace which jobs and builds a given file appeared in.
  • Test results are saved in the build directory's junitResult.xml, and aggregated into a trend graph.
  • The image itself stays in the host's dockerd (because agent1 uses the host's docker.sock). docker image ls myapp It is visible on the host.

When: whether to clean the workspace

ApproachBenefitCost
post { cleanup { cleanWs() } } (this lesson)Every build is clean and is not affected by leftovers from the last buildRecreates the venv and downloads dependencies every time
Keep the workspaceIncremental and fastLeftover files can make a build “pass on CI but fail elsewhere”
Dependency cache (pip cache directory, internal PyPI mirror)Clean and fastRequires extra configuration (Lesson 7)
Common misconceptions① “Archiving the tar from docker save makes it easy to download”— this quickly fills the controller's disk and slows every build. ② “Building myapp:1.0 means it is released”— it only exists in this machine's dockerd; Lessons 3 and 4 push it to ACR / ECR. ③ “The test report can sit in the same steps as sh”— when sh fails, the later steps in the same steps block do not run, so the report must go in post. ④ “myapp:1.0 Overwriting it each time is fine”— mutable tags cannot be traced, so also apply an immutable myapp:$BUILD_NUMBER and write a revision label.

CI pipeline and where artifacts go

Checkoutgitea-myapp Testpytest → junit.xml Build imagemyapp:1.0 / :N Smoke test/healthz = 200 Archivereports/** postcleanWs() controller · JENKINS_HOMEjobs/myapp/builds/N/junitResult.xmljobs/myapp/builds/N/archive/reports/**fingerprints/ (MD5 → build) host dockerd (via docker.sock)Images myapp:1.0 and myapp:N (label revision=GIT_COMMIT)Temporary container myapp-ci-N (removed after the smoke test)Lessons 3 and 4: push to ACR / ECR
Figure 7-1: test reports and archived files return to the controller; the image stays in dockerd; the workspace is cleaned up in post cleanup

Why the smoke test uses docker exec

agent1 containerNetwork: jenkinslab_cidocker CLI → host dockerdcurl http://myapp-ci-N:5000 ✗(not on the same network, so the name cannot be resolved) myapp-ci-N containerNetwork: default bridgegunicorn :5000docker exec … urlopen('http://localhost:5000/healthz') ✓ docker exec (via dockerd, not over the network)
Figure 7-2 “Docker outside of Docker”: containers started by the agent are sibling containers on the host, not on the compose network; an in-container self-check is the simplest and most reliable option

Stage view simulator

Simulates one build in the Pipeline Graph View. Choose a fault injection and watch which stages change color, which stages are skipped, the final result, and the key console log lines.

Ready.

Command table

Step / interfacePurposeKey parameters
junitParse JUnit XML and record test resultstestResults,allowEmptyResults
archiveArtifactsCopy workspace files to the controllerartifacts,fingerprint,allowEmptyArchive,onlyIfSuccessful
cleanWs()Delete the workspace (Workspace Cleanup plugin)patterns,deleteDirs
catchErrorCatch errors and set the build / stage resultbuildResult,stageResult
GET /job/myapp/lastBuild/testReport/api/jsonRead test statisticstree=passCount,failCount,skipCount
GET /job/myapp/lastSuccessfulBuild/api/jsonList artifactstree=number,artifacts[relativePath]

Complete Jenkinsfile (Lesson 2 continues from this)

// ~/jenkinslab/myapp/Jenkinsfile (full version of Lesson 1)
pipeline {
  agent { label 'linux && docker' }

  options {
    timestamps()
    timeout(time: 15, unit: 'MINUTES')
    buildDiscarder(logRotator(numToKeepStr: '20', artifactNumToKeepStr: '5'))
    disableConcurrentBuilds()
  }

  environment {
    IMAGE   = 'myapp'
    VERSION = '1.0'
  }

  stages {
    stage('Test') {
      steps {
        sh '''
          python3 -m venv .venv
          . .venv/bin/activate
          pip install --quiet -r requirements-dev.txt
          mkdir -p reports
          python -m pytest -q --junitxml=reports/junit.xml
        '''
      }
      post {
        always { junit testResults: 'reports/junit.xml', allowEmptyResults: true }
      }
    }

    stage('Build image') {
      steps {
        sh '''
          docker build --pull \
            -t "$IMAGE:$VERSION" -t "$IMAGE:$BUILD_NUMBER" \
            --label "org.opencontainers.image.revision=$GIT_COMMIT" \
            --label "org.opencontainers.image.source=http://gitea:3000/lab/myapp" \
            .
        '''
      }
    }

    stage('Smoke test') {
      steps {
        sh '''
          CID=$(docker run -d --rm --name "myapp-ci-$BUILD_NUMBER" "$IMAGE:$BUILD_NUMBER")
          trap 'docker rm -f "$CID" >/dev/null 2>&1 || true' EXIT
          for i in $(seq 1 20); do
            if docker exec "$CID" python -c "import urllib.request; urllib.request.urlopen('http://localhost:5000/healthz', timeout=2)" 2>/dev/null; then
              echo "healthz OK after ${i}s"; exit 0
            fi
            sleep 1
          done
          echo "healthz FAILED"; docker logs "$CID"; exit 1
        '''
      }
    }

    stage('Archive') {
      steps {
        sh '''
          docker image inspect "$IMAGE:$BUILD_NUMBER" --format '{{json .}}' \
            | python3 -c 'import sys,json,os; d=json.load(sys.stdin); json.dump({"image": os.environ["IMAGE"]+":"+os.environ["VERSION"], "build": os.environ["BUILD_NUMBER"], "id": d["Id"], "revision": os.environ["GIT_COMMIT"], "size": d["Size"]}, open("reports/build-info.json","w"), indent=2)'
          cat reports/build-info.json
        '''
        archiveArtifacts artifacts: 'reports/**', fingerprint: true
      }
    }
  }

  post {
    success { echo "Built ${env.IMAGE}:${env.VERSION} (also tagged :${env.BUILD_NUMBER})" }
    failure { echo 'Build failed - see Test Result and console log' }
    cleanup { cleanWs() }
  }
}

$GIT_COMMIT from the Declarative automatic checkout (environment variables set by the Git plugin). {{json .}} is a Docker Go template; written inside a single-quoted shell string, it is interpreted by neither Groovy nor the shell.

Verify the build result

JT=$(cat ~/jenkinslab/.secrets/jenkins-token)
curl -s -u "admin:$JT" "http://localhost:8080/job/myapp/lastBuild/testReport/api/json?tree=passCount,failCount,skipCount"; echo
curl -s -u "admin:$JT" "http://localhost:8080/job/myapp/lastSuccessfulBuild/api/json?tree=number,result,artifacts[relativePath]"; echo
docker image ls myapp
docker image inspect myapp:1.0 --format '{{index .Config.Labels "org.opencontainers.image.revision"}}'
{"_class":"hudson.tasks.junit.TestResult","failCount":0,"passCount":2,"skipCount":0}
{"_class":"org.jenkinsci.plugins.workflow.job.WorkflowRun","artifacts":[{"relativePath":"reports/build-info.json"},{"relativePath":"reports/junit.xml"}],"number":4,"result":"SUCCESS"}
REPOSITORY   TAG       IMAGE ID       CREATED          SIZE
myapp        1.0       0f3b9c2d7a11   40 seconds ago   171MB
myapp        4         0f3b9c2d7a11   40 seconds ago   171MB
5c7e2a1d9b0e4f3a2c1b8d7e6f5a4b3c2d1e0f9a

Goal: Commit the full Jenkinsfile and build myapp:1.0, run it; then deliberately make one test fail and observe FAILURE and the test report. Environment: Modules 0–6. Cost: None (the image takes about 200 MB of disk).

Update the Jenkinsfile and push: overwrite it with the full version from the “Commands” tab ~/jenkinslab/myapp/Jenkinsfile:
cd ~/jenkinslab/myapp
jcli declarative-linter < Jenkinsfile
git add Jenkinsfile && git commit -m "ci: test, build image, smoke test, archive"
AUTH=$(printf 'lab:%s' "$(cat ../.secrets/gitea-token)" | base64 | tr -d '\n')
git -c http.extraHeader="Authorization: Basic $AUTH" push
jcli build myapp -s -v | grep -E "passed|Successfully tagged|naming to|healthz|Archiving|Recording|Finished"
10:31:12  2 passed in 0.23s
10:31:12  Recording test results
10:31:40  #8 naming to docker.io/library/myapp:1.0 done
10:31:40  #8 naming to docker.io/library/myapp:4 done
10:31:43  healthz OK after 2s
10:31:44  Archiving artifacts
10:31:44  Recording fingerprints
Finished: SUCCESS
Run the image on the host (delete it after the demo):
docker run -d --rm --name myapp-try -p 127.0.0.1:5000:5000 myapp:1.0
sleep 2; curl -s http://127.0.0.1:5000/healthz; curl -s http://127.0.0.1:5000/
docker rm -f myapp-try
{"status":"ok"}
Hello from 3a9f1c2b7d4e, hits=N/A (redis not connected)
Check artifacts and fingerprints: in the browser, open the build page → Build Artifacts (reports/build-info.json,reports/junit.xml) → click “See fingerprints” next to a file to see which build produced it.
Deliberately make a test fail:
cd ~/jenkinslab/myapp
sed -i 's/{"status": "ok"}/{"status": "degraded"}/' app.py
git commit -am "break: healthz says degraded" && git -c http.extraHeader="Authorization: Basic $AUTH" push
jcli build myapp -s | tail -n 1
curl -s -u "admin:$(cat ../.secrets/jenkins-token)" "http://localhost:8080/job/myapp/lastBuild/testReport/api/json?tree=failCount,passCount"; echo
Completed myapp #5 : FAILURE
{"_class":"hudson.tasks.junit.TestResult","failCount":1,"passCount":1}

The Build image, Smoke test and Archive stages show as skipped (grey), and the Test Result page shows test_healthz the assertion differences.

Fix it and restore green:
git revert --no-edit HEAD && git -c http.extraHeader="Authorization: Basic $AUTH" push
jcli build myapp -s | tail -n 1
Completed myapp #6 : SUCCESS
Cleanup: keep myapp:1.0 the image and job; you can delete the numbered tags docker image ls myapp --format '{{.Tag}}' | grep -E '^[0-9]+$' | xargs -r -I{} docker image rm myapp:{}.

Case 1: controller disk filled by artifacts

Problem: One job archives 1.2 GB of docker save output each time; three weeks later the controller disk was full and Jenkins refused new builds. Fix: Push images to an image registry, have Jenkins archive only build-info.json, and add artifactNumToKeepStr; clean up old large artifacts with a script. Limitation: Requires an image registry (Lessons 3 and 4).

Case 2: smoke test leaves containers behind

Problem: When the smoke test failed, the script exited early and the test container was not removed; a few days later the host had hundreds of leftover containers holding ports. Fix: Use trap … EXIT to guarantee cleanup, and add --rm, do not map host ports, and clean up periodically docker container prune --filter "label=…". Limitation: If the agent is forcibly killed, the trap will not run either, so periodic cleanup jobs are needed.

Case 3: using fingerprints to trace “who used this build artifact”

Problem: A problematic jar was referenced by several downstream projects, and the blast radius was unknown. Fix: Upstream records fingerprints when archiving; downstream jobs fetch via copyArtifacts and record fingerprints the same way, so Jenkins can show which builds the file appears in. Limitation: Only files recorded through Jenkins fingerprinting can be tracked; tracing container images is better done with image digests + SBOM.

Common errors and fixes

permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock

Cause: The jenkins user in agent1 is not in the group that owns docker.sock (DOCKER_GID in .env is wrong, or the container was not rebuilt after the change).

docker compose exec agent1 sh -c 'id; stat -c "%g %n" /var/run/docker.sock'
grep DOCKER_GID ~/jenkinslab/.env

Fix: Change DOCKER_GID to the group ID seen inside the container,docker compose up -d agent1 then rebuild.

ERROR: Step ‘Publish JUnit test result report’ failed: No test report files were found. Configuration error?

Cause: pytest did not generate a report (without adding --junitxml, a path mismatch, or pytest crashing during collection).

Fix: Check that --junitxml=reports/junit.xml matches junit's testResults; when you need to tolerate “no report”, add allowEmptyResults: true (this lesson already includes it).

ModuleNotFoundError: No module named 'app'

Cause: When running pytest directly, the test directory is added to sys.path, but the project root directory is not.

Fix: Use python -m pytest (adds the current directory to the path), or set pythonpath = . in pytest.ini (this lesson does both).

healthz FAILED … [ERROR] Worker failed to boot / ModuleNotFoundError (docker logs output)

Cause: A file is missing from the image (for example, .dockerignore excluded a needed file) or a dependency was not installed.

docker run --rm myapp:1.0 ls /app
docker run --rm myapp:1.0 pip list | grep -iE "flask|gunicorn|redis"

Fix: Check the Dockerfile's COPY and .dockerignore (this lesson only COPYs app.py).

Command-line task
1. Use REST to query the number of failed test cases in myapp's most recent build.
curl -s -u "admin:$JT" "http://localhost:8080/job/myapp/lastBuild/testReport/api/json?tree=failCount"
2. Write the steps to archive the reports directory and record its fingerprints.
archiveArtifacts artifacts: 'reports/**', fingerprint: true
Scenario analysis
The product manager wants “images still built when tests fail, so QA can reproduce.” How would you weigh this and implement it?

By default, releasable images should not be built for code that fails tests. If it is truly needed, use catchError(buildResult: 'UNSTABLE', stageResult: 'UNSTABLE') to wrap the tests so the build continues, and tag the image only with a non-releasable label (such as myapp:ci-$BUILD_NUMBER-unstable), and do not apply 1.0; in the later push / deploy stages add when { expression { currentBuild.currentResult == 'SUCCESS' } } a guard; record the test status in build-info.json.

Verified instructional videos

▶
Jenkins Tutorial – How to Deploy a Test Server with Docker + Linux (Full Course) — freeCodeCamp.org
English · about 1 hour · complete workflow for building and testing applications with Jenkins and Docker; the version is older, so follow this lesson for current security practice
▶
Jenkins Full Course | Jenkins Tutorial For Beginners | Jenkins Tutorial | Simplilearn — Simplilearn
English · long comprehensive course; you can skip ahead to the chapters on builds, test reports and artifacts

Official documentation

Video storyboard script (about 90 seconds)

This courseware cannot directly generate video or MP3, so a storyboard and narration script are provided instead.

Shot 1 · 0–20s
Visual: five stages laid out horizontally, the Test stage lights up, and pytest outputs two green dots.
Narration: test first, then hand the test report to Jenkins in JUnit format.
Shot 2 · 20–45s
Visual: docker build layers complete one by one, and the image gets two tags, 1.0 and the build number.
Narration: build the image only after the tests pass, and apply both a mutable tag and an immutable build-number tag.
Shot 3 · 45–70s
Visual: a temporary container starts, a heartbeat icon shows healthz OK, and then the container disappears.
Narration: the smoke test requests the health check from inside the container, and the container is cleaned up afterwards, whether it passed or failed.
Shot 4 · 70–90s
Visual: two small files fly back to the controller's filing cabinet, while the image stays in the Docker engine.
Narration: archive only the small reports on the controller; images are pushed to an image registry later.
or score ≥ 70% on the “Quiz”

Module 8 · Build readiness review and troubleshooting basics

50:00 – 60:00 · Use a 12-item checklist to verify whether the lab environment is “ready for Lesson 2”, and build a symptom-driven troubleshooting method
10 minutes12-item readiness reviewInteractive troubleshooting tree★★★★★
Learning goals
  • Use the 12-item build readiness review to check the Jenkins instance (architecture, version, plugins, credentials, Jenkinsfile, backup).
  • Classify failures by “which step the build is stuck at”: queueing, checkout, step execution, and the platform itself, and know what to check first for each category.
  • Collect diagnostic information: console logs, the queue API, node logs, container logs, and the system log (Manage Jenkins → System Log).
  • Inject and fix 4 typical faults in the lab.
Prerequisites: Modules 1–7. Importance:★★★★★

What: the 12-item build readiness review

#Check itemHow to verifyRelated module
1Use a pinned LTS version tag (2.580.2-jdk21), Java 21/25jcli version; compose.yamlM2
2Built-in node executors = 0/computer/api/json in the Built-In Node's numExecutorsM1
3At least one online agent, with labels named by capabilityagent1 online, label linux dockerM1
4JENKINS_HOME is on a persistent volume, and there is an encrypted backup that can be restoreddocker volume ls; the backup fileM2
5the plugin list has been exported (plugins.txt), with no unresolved security warningsNo red banner at the top of Manage JenkinsM3
6Job configuration comes from SCM (Jenkinsfile in the repository root)jcli get-job myappM4, M5
7Jenkinsfile has timeout, buildDiscarder, and an explicit agent labelReview the Jenkinsfile; linter passesM5
8Credentials use a consistent ID (gitea-myapp), and the value is a scope-limited token, not a passwordlist-credentialsM6
9No interpolated secrets in the Jenkinsfile (no interpolation warnings)Search the console for “Groovy String interpolation”M6
10The test report is recorded, and a test failure produces no imageTest Result page; failed builds skip Build imageM7
11Artifacts: only small files are archived, with fingerprints recordedBuild page Build ArtifactsM7
12Exposed only on 127.0.0.1; the docker.sock risk has been recorded and accepted (lab only)docker compose ps in the PORTS column ofM0, M1

Why: first locate “which step it is stuck at”

The Module 1 lifecycle is your troubleshooting map. The stage where the symptom appears determines what to look at:

StageTypical symptomCheck first
Queue (②–④)The build spins grey indefinitely; “Still waiting to schedule task”Hover tooltip on the queue entry / /queue/api/json of why; Nodes page
Checkout (⑤)Authentication failed,Failed to connect,Unable to find Jenkinsfilefirst 30 lines of the console; manually run it in the agent container git ls-remote
Steps (⑥)script returned exit code N, permission denied, command not foundOutput above the failed step in the console; reproduce the command on the agent
PlatformSlow UI, plugin load failures, frequent agent disconnectsManage Jenkins → System Log; docker compose logs; resource usage

How: where to find diagnostic information

  • Console log: /job/myapp/N/console, plain text /job/myapp/N/consoleText, CLI jcli console myapp N.
  • Pipeline step view: Pipeline Graph or /job/myapp/N/flowGraphTable/ (duration and status of each step).
  • Node log: /computer/agent1/log (connection log as seen from the controller side) + docker compose logs agent1 (agent side).
  • System log: Manage Jenkins → System Log; the controller container's docker compose logs jenkins.
  • System information: Manage Jenkins → System Information (Java, system properties, environment variables, plugin list).

When: when to escalate to “deep troubleshooting”

When a problem is related to load or timing (occasional stalls, steadily growing memory, queues piling up at peak times), you need thread dumps, GC logs and Prometheus metrics; these are covered in Lesson 7. This module addresses “deterministic” configuration and connectivity problems.

Common misconceptions① “Retry a failed build a few times first”— retrying a deterministic error is pointless, so read the log to locate the stage first. ② “If an agent goes offline, restart the controller”— check the agent-side logs first; the problem is usually the agent process or container. ③ “The log is too long, so only read the last line”—Finished: FAILURE the first error, earlier in the log, is the root cause; what follows is mostly a chain reaction.

Layered diagram from symptom to root cause

Queue stuckNo matching labelExecutors exhaustedNode offlineBlocked (concurrency limit) Checkout failureURL uses localhostInvalid credential ID / tokenWrong branch / Script PathGitea unreachable Step failureTest failuredocker.sock permissionMissing tool (python3-venv)Syntax / quoting error Platform issuePlugin load failureDisk full / out of memoryUpdate Center unreachableVersion / Java incompatibility Diagnostic entry point /queue/api/json · Nodes pagefirst 30 lines of console · git ls-remoteoutput above the failed step · reproduce on the agentSystem Log · compose logs · df
Figure 8-1: the four symptom types map to the four segments of the Module 1 lifecycle; each has a fixed first diagnostic entry point

Readiness review coverage

Platform#1 version · #2 built-in node#4 backup · #12 exposure Capacity#3 agents and labels#5 plugin list Pipeline#6 SCM · #7 timeout/discard#10 tests · #11 artifacts Security#8 tokens, not passwords#9 no interpolated secrets
Figure 8-2: the 12 checks span four dimensions: platform, capacity, pipeline and security

Interactive: build readiness review scorer

Check items one by one against your lab environment. Scores are weighted by risk (security and platform items carry more weight), and failed items show a fix command. Results are saved in this browser.

Review result
0 / 100

Command table: diagnostic toolbox

CommandWhat it shows
jcli console myapp [N]Full console for a given build
curl …/queue/api/json?tree=items[task[name],why,stuck]Queue reason
curl …/computer/api/json?tree=computer[displayName,offline,offlineCauseReason]Node offline reason
docker compose logs --since 15m jenkins agent1 giteaRecent logs for the three services
docker compose exec agent1 git ls-remote http://gitea:3000/lab/myapp.gitReproduce checkout from the agent's perspective (prompts when credentials are needed)
docker system df,docker compose exec jenkins df -h /var/jenkins_homeDisk

One-step diagnostic collection

cd ~/jenkinslab
JT=$(cat .secrets/jenkins-token); OUT=diag-$(date +%H%M%S); mkdir -p "$OUT"
docker compose ps > "$OUT/ps.txt"
docker compose logs --since 30m > "$OUT/compose.log" 2>&1
curl -s -u "admin:$JT" "http://localhost:8080/queue/api/json?tree=items[id,task[name],why,stuck,inQueueSince]" > "$OUT/queue.json"
curl -s -u "admin:$JT" "http://localhost:8080/computer/api/json?tree=computer[displayName,offline,offlineCauseReason,numExecutors,idle]" > "$OUT/nodes.json"
curl -s -u "admin:$JT" "http://localhost:8080/job/myapp/lastBuild/consoleText" > "$OUT/last-console.txt"
docker compose exec -T jenkins df -h /var/jenkins_home > "$OUT/disk.txt"
grep -nE "ERROR|Exception|FAILURE|denied|refused" "$OUT/last-console.txt" | head -n 20
ls "$OUT"
57:permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock
60:ERROR: script returned exit code 1
64:Finished: FAILURE
compose.log  disk.txt  last-console.txt  nodes.json  ps.txt  queue.json

How to verify: All 6 files in the directory are non-empty. Common mistake: queue.json being {"items":[]} is normal (nothing is queued at the moment). Production use: Attach this information when submitting a ticket; note that compose.log and the console may contain sensitive information, so check before sharing.

Goal: Inject 4 faults in turn, and locate and fix each one using this module's methods. Environment: Module 7 completed, with myapp building green. Cost: None. Restore after each fault.

Fault 1: agent offline → build queued
cd ~/jenkinslab
docker compose stop agent1
jcli build myapp &                    # without -s, returns immediately
sleep 8; curl -s -u "admin:$(cat .secrets/jenkins-token)" "http://localhost:8080/queue/api/json?tree=items[task[name],why]"; echo
{"_class":"hudson.model.Queue","items":[{"task":{"name":"part of myapp #7"},"why":"‘agent1’ is offline"}]}

Fix:docker compose start agent1, and the build starts automatically a few seconds later. Note that what is queued is “part of myapp #7” — the Pipeline itself has already started (on the controller) and is waiting for agent block's executor.

Fault 2: wrong label: in Replay, change label 'linux && docker' to label 'linux && dokcer' → Run. The console shows Still waiting to schedule task and There are no nodes with the label ‘linux&&dokcer’ (the label expression is normalized in display). Fix: Stop the build (red cross on the left), and change the label back to the correct one.
Fault 3: token revoked → checkout failure: in the Gitea web UI, go to lab → Settings → Applications and delete the token currently used by Jenkins, then jcli build myapp -s -v | head -n 30, and see Authentication failed (or the authentication error when the controller reads the Jenkinsfile). Fix: Generate a new token as in Module 6 and update-credentials-by-xml, then rebuild.
Fault 4: docker.sock permission
cd ~/jenkinslab
cp .env .env.bak && sed -i 's/^DOCKER_GID=.*/DOCKER_GID=12345/' .env
docker compose up -d agent1 && sleep 10
jcli build myapp -s -v | grep -E "permission denied|Finished"
permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: …
Finished: FAILURE

Fix:mv .env.bak .env && docker compose up -d agent1, then build again; it should be SUCCESS. Observe: the Test stage passes, and the failure starts at Build image — “look at the first error”.

Complete the readiness review: check items one by one in the scorer on the “Animation” tab, aiming for ≥ 90 points. Fix failed items as the prompts indicate.
Cleanup: confirm agent1 is online, myapp's latest build is SUCCESS,.env is restored. Keep the environment running, or docker compose stop,do not down -v, as Lesson 2 continues to use it.

Case 1: “everything queued” on Monday morning

Problem: All builds were queued, and the UI showed “Waiting for next available executor”. Diagnosis: The queue API showed the same label as the reason for every build; on the Nodes page, all three agents were offline, with the offline reason “Disk space is too low” (the node monitor automatically takes a node offline when disk space falls below the threshold). Fix: Clean up old workspaces and the Docker image cache on the agents, and configure a scheduled cleanup job and disk alerts. Limitation: The node monitor threshold must match the workspace size; a threshold that is too high causes frequent false offline events.

Case 2: intermittent checkout failures

Problem: About 5% of builds failed at checkout, and rerunning them fixed it. Diagnosis: The console showed HTTP 429 / timeouts; the Git server has rate limiting, and multiple jobs were polling SCM at the same time. Fix: Switch to webhook triggers (Lesson 2) and remove the intensive polling; add retry. Limitation: Webhooks require the Git server to be able to reach Jenkins.

Case 3: readiness review built into the change process

Problem: When new teams join the shared Jenkins, they often lack a timeout, hard-code node names, or use personal passwords. Fix: Turn this module's 12-item checklist into an onboarding review template; the Shared Library provides default options; credentials accept only service-account tokens. Limitation: The checklist must be updated regularly as versions and security advisories change.

Interactive troubleshooting tree

Answer questions step by step, starting from the symptom, to get a diagnosis and a fix command. Covers the most common faults in this lesson's lab environment.

Supplement: three most common errors

Still waiting to schedule task / There are no nodes with the label ‘linux&&docker’

Cause: agent1 is offline, or its labels do not include linux and docker.

curl -s -u "admin:$JT" "http://localhost:8080/computer/agent1/api/json?tree=offline,offlineCauseReason,assignedLabels[name]"

Fix: Start agent1 / correct the node labels.

hudson.plugins.git.GitException: Command "git fetch …" returned status code 128

Cause: status 128 is Git's generic failure code; look at the line that follows stderr: saying: authentication, network, or the repository does not exist.

Fix: Follow the Module 4 / 6 troubleshooting entries based on the stderr content.

ERROR: script returned exit code 1

Cause: A sh step's last command (or set -e any command under it) failed. This line itself is not the root cause.

Fix: Look upward for the first error line from that sh; reproduce it by running the same command manually inside the agent container: docker compose exec agent1 bash.

Command-line task
1. Find out with one command why agent1 is offline.
curl -s -u "admin:$JT" "http://localhost:8080/computer/agent1/api/json?tree=offline,offlineCauseReason"
2. Extract all lines containing ERROR from the console of myapp's most recent build.
curl -s -u "admin:$JT" http://localhost:8080/job/myapp/lastBuild/consoleText | grep -n ERROR
Scenario analysis
A new colleague says: “The myapp build keeps spinning; the log only shows Started by user and Obtained Jenkinsfile, and then nothing happens.” Give the troubleshooting steps.

The Jenkinsfile was read (controller access to Gitea is working), which means it is stuck at the scheduling of the agent block (lifecycle ②–④). ① Check the queue: /queue/api/json of why; ② if it says “no nodes with the label”, check the Jenkinsfile label against agent1's labels; ③ if it says “is offline”: docker compose ps agent1,docker compose logs agent1, check the secret and port 50000; ④ if it says “Waiting for next available executor”, check whether agent1 has a hung build (missing timeout), abort it if necessary and add the timeout; ⑤ once fixed, the build continues automatically, with no need to retrigger.

Verified instructional videos

No verified video focused on “Jenkins build readiness review and troubleshooting methods” was found. Comprehensive supplementary material:

▶
Jenkins Full Course | Jenkins Tutorial For Beginners | Jenkins Tutorial | Simplilearn — Simplilearn
English · long comprehensive course, useful for review; for troubleshooting methods, follow this module

Official documentation

Video storyboard script (about 90 seconds)

This courseware cannot directly generate video or MP3, so a storyboard and narration script are provided instead.

Shot 1 · 0–20s
Visual: the Module 1 lifecycle diagram, with its four segments labeled “queue, checkout, steps, platform”.
Narration: when troubleshooting, first ask one question: which segment is the build stuck in?
Shot 2 · 20–45s
Visual: the queue entry hover tooltip says is offline; the terminal shows docker compose logs agent1 scrolling.
Narration: for a queued build, check the queue reason and the node logs; most cases are label mismatches or offline nodes.
Shot 3 · 45–70s
Visual: console log, scrolling up to find the first red error.
Narration: for failures, look at the first error; the last line is just the result.
Shot 4 · 70–90s
Visual: the twelve-item checklist is ticked off one by one, and the score rises above ninety.
Narration: use the twelve-item readiness review to hand the environment over to the next lesson.
or score ≥ 70% on the “Quiz”

Command cheat sheet

All common commands, Jenkinsfile snippets and a quick troubleshooting reference for this lesson
Jenkins 2.580.2~/jenkinslab

Environment lifecycle

cd ~/jenkinslab
docker compose up -d jenkins gitea     # first time (agent1 needs the secret)
docker compose up -d                   # afterwards
docker compose ps
docker compose logs -f --since 10m jenkins
docker compose stop                    # pause, keep data
docker compose down -v                 # ⚠ deletes all data

Initialization and identity

docker compose exec jenkins cat /var/jenkins_home/secrets/initialAdminPassword
curl -sI http://localhost:8080/login | grep -i '^x-jenkins:'
curl -s -u "admin:$(cat .secrets/jenkins-token)" http://localhost:8080/whoAmI/api/json

Jenkins CLI (jcli function)

jcli() { docker compose -f ~/jenkinslab/compose.yaml exec -T \
  -e JENKINS_USER_ID=admin -e JENKINS_API_TOKEN="$(cat ~/jenkinslab/.secrets/jenkins-token)" \
  jenkins java -jar /var/jenkins_home/jenkins-cli.jar -s http://localhost:8080/ "$@"; }
jcli version; jcli who-am-i
jcli list-jobs; jcli get-job myapp > myapp.xml
jcli build myapp -s -v; jcli console myapp
jcli safe-restart

Nodes and queue

J=http://localhost:8080; A="admin:$(cat .secrets/jenkins-token)"
curl -s -u "$A" "$J/computer/api/json?tree=computer[displayName,offline,numExecutors,assignedLabels[name]]"
curl -s -u "$A" "$J/queue/api/json?tree=items[task[name],why,stuck]"
curl -s -u "$A" $J/computer/agent1/jenkins-agent.jnlp   # includes secret
docker compose logs agent1 | tail

Plugins

jcli install-plugin gitea docker-workflow -deploy
jcli list-plugins | grep -E '^(git|gitea|junit) '
curl -s -u "$A" "$J/pluginManager/api/json?depth=1&tree=plugins[shortName,version]"
# Dockerfile: RUN jenkins-plugin-cli --plugin-file /usr/share/jenkins/ref/plugins.txt

Credentials

jcli list-credentials system::system::jenkins
jcli create-credentials-by-xml system::system::jenkins _ < cred.xml
jcli update-credentials-by-xml system::system::jenkins _ gitea-myapp < cred.xml
docker compose exec -T -u git gitea gitea admin user generate-access-token \
  --username lab --token-name jenkins-myapp --scopes write:repository

Jenkinsfile skeleton

pipeline {
  agent { label 'linux && docker' }
  options { timestamps(); timeout(time: 15, unit: 'MINUTES')
            buildDiscarder(logRotator(numToKeepStr: '20')) }
  environment { IMAGE = 'myapp'; VERSION = '1.0' }
  stages {
    stage('Test') {
      steps { sh 'python -m pytest --junitxml=reports/junit.xml' }
      post  { always { junit 'reports/junit.xml' } }
    }
  }
  post { cleanup { cleanWs() } }
}

Credentials and artifact snippets

withCredentials([usernamePassword(credentialsId: 'gitea-myapp',
    usernameVariable: 'U', passwordVariable: 'T')]) {
  sh 'curl -sf -u "$U:$T" http://gitea:3000/api/v1/repos/lab/myapp'
}
archiveArtifacts artifacts: 'reports/**', fingerprint: true
catchError(buildResult: 'UNSTABLE', stageResult: 'UNSTABLE') { sh '…' }

Quick troubleshooting table

Symptom / errorMost likely causeFirst command
There are no nodes with the label …Label typo / agent missing label…/computer/api/json?tree=computer[displayName,assignedLabels[name]]
‘agent1’ is offlineagent container stopped, wrong secretdocker compose logs agent1
Waiting for next available executorexecutors exhausted / build hungNodes page, to see running builds
Failed to connect to localhost port 3000localhost used inside the containerchange to http://gitea:3000/…
Authentication failedinvalid token / wrong credential IDcurl -u lab:TOKEN …/api/v1/repos/lab/myapp
Unable to find Jenkinsfilefile not found / wrong branch or pathgit ls-tree origin/main
permission denied … docker.sockwrong DOCKER_GIDdocker compose exec agent1 id
No such DSL methodmissing pluginjcli list-plugins
A secret was passed to "sh" using Groovy String interpolationsecret interpolated in double quotesswitch to single-quoted sh
Timeout has been exceededstep stucktimestamped log to find the slow step

Recommended configuration snippet: the agent service in compose

agent1:
  build: ./agent
  init: true
  command: ["-url", "http://jenkins:8080", "-workDir=/home/jenkins/agent", "${AGENT1_SECRET:-not-set}", "agent1"]
  group_add: ["${DOCKER_GID:-999}"]
  volumes:
    - agent1_work:/home/jenkins/agent
    - /var/run/docker.sock:/var/run/docker.sock   # lab only
  # If only HTTP(S) can be opened: add "-webSocket" to command

Capstone lab + final quiz

Turn this lesson's manual steps into a repeatable bootstrap script, rebuild the environment from scratch, and accept myapp:1.0
≈ 30 minutesLocal · freeDeletes and rebuilds the lab environment

Scenario

A new colleague wants to get the same ~/jenkinslab. You decide to script the configuration of Gitea and Jenkins: only the steps that still have to be done in the browser are kept — “unlock + install suggested plugins + create admin + generate API token + create node” (Lesson 5 automates these too, using JCasC) — everything else is done with commands, and finally an acceptance checklist proves that the environment can be handed over to Lesson 2.

Back up first This lab uses docker compose down -v to delete the existing lab data. If you want to keep the current environment, first back it up following Module 2 jenkins_home, or put the whole lab in another directory (for example ~/jenkinslab2, and change the compose name name and ports).
Destroy and rebuild the base services
cd ~/jenkinslab
docker compose down -v
sed -i 's/^AGENT1_SECRET=.*/AGENT1_SECRET=/' .env
docker compose up -d jenkins gitea
until docker compose logs jenkins 2>&1 | grep -q "Jenkins is fully up and running"; do sleep 3; done
docker compose exec jenkins cat /var/jenkins_home/secrets/initialAdminPassword
Minimum steps to complete in the browser: unlock → Install suggested plugins → create admin → Jenkins URL http://localhost:8080/ → generate the API token and write it to .secrets/jenkins-token → set Built-In Node executors to 0 → create node agent1 (2 executors,/home/jenkins/agent, label linux docker, only runs matching jobs, inbound connection).
Write the bootstrap script bootstrap.sh (Gitea, agent, plugins, credentials and jobs, all done via commands):
cat > ~/jenkinslab/bootstrap.sh <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
cd ~/jenkinslab
J=http://localhost:8080; A="admin:$(cat .secrets/jenkins-token)"
jcli() { docker compose exec -T -e JENKINS_USER_ID=admin -e JENKINS_API_TOKEN="$(cat .secrets/jenkins-token)" \
  jenkins java -jar /var/jenkins_home/jenkins-cli.jar -s http://localhost:8080/ "$@"; }

echo "== 1. Jenkins CLI"
docker compose exec -T jenkins curl -sSo /var/jenkins_home/jenkins-cli.jar $J/jnlpJars/jenkins-cli.jar
jcli version

echo "== 2. agent1"
S=$(curl -s -u "$A" $J/computer/agent1/jenkins-agent.jnlp | sed -n 's|.*<argument>\([0-9a-f]\{64\}\)</argument>.*|\1|p')
[ -n "$S" ] || { echo "agent1 node does not exist or has no permission"; exit 1; }
sed -i "s/^AGENT1_SECRET=.*/AGENT1_SECRET=$S/" .env
docker compose up -d agent1

echo "== 3. Gitea users, tokens, repositories
GITEA_PASS=${GITEA_PASS:?export GITEA_PASS first}
until curl -sf http://localhost:3000/api/v1/version >/dev/null; do sleep 2; done
docker compose exec -T -u git gitea gitea admin user create --username lab --password "$GITEA_PASS" \
  --email lab@example.com --admin --must-change-password=false || true
docker compose exec -T -u git gitea gitea admin user generate-access-token --username lab \
  --token-name "jenkins-myapp-$(date +%s)" --scopes write:repository | awk '{print $NF}' > .secrets/gitea-token
curl -s -o /dev/null -w "create repo: %{http_code}\n" -u "lab:$GITEA_PASS" -H "Content-Type: application/json" \
  -X POST http://localhost:3000/api/v1/user/repos -d '{"name":"myapp","private":true,"default_branch":"main"}'
AUTH=$(printf 'lab:%s' "$(cat .secrets/gitea-token)" | base64 | tr -d '\n')
git -C myapp remote set-url origin http://localhost:3000/lab/myapp.git
git -C myapp -c http.extraHeader="Authorization: Basic $AUTH" push -u origin main

echo "== 4. Plugins
jcli install-plugin gitea docker-workflow -deploy

echo "== 5. Credentials gitea-myapp
umask 077
printf '<com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl><scope>GLOBAL</scope><id>gitea-myapp</id><description>Gitea user lab token for lab/myapp</description><username>lab</username><password>%s</password></com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl>' \
  "$(cat .secrets/gitea-token)" | jcli create-credentials-by-xml system::system::jenkins _

echo "== 6. Job myapp"
jcli create-job myapp < myapp-job.xml

echo "== 7. Build
jcli build myapp -s | tail -n 1
EOF
chmod +x ~/jenkinslab/bootstrap.sh
Run the script:
read -rsp "Gitea lab password: " GITEA_PASS; echo; export GITEA_PASS
~/jenkinslab/bootstrap.sh
== 1. Jenkins CLI
2.580.2
== 2. agent1
 ✔ Container agent1  Started
== 3. Gitea users, tokens, repositories
create repo: 201
== 4. Plugins
== 5. Credentials gitea-myapp
== 6. Job myapp
== 7. Build
Completed myapp #1 : SUCCESS
Acceptance commands:
cd ~/jenkinslab; J=http://localhost:8080; A="admin:$(cat .secrets/jenkins-token)"
curl -s -u "$A" "$J/computer/api/json?tree=computer[displayName,offline,numExecutors]"; echo
curl -s -u "$A" "$J/job/myapp/lastBuild/api/json?tree=number,result,artifacts[relativePath]"; echo
curl -s -u "$A" "$J/job/myapp/lastBuild/testReport/api/json?tree=passCount,failCount"; echo
docker image inspect myapp:1.0 --format '{{.Id}} {{index .Config.Labels "org.opencontainers.image.revision"}}'
curl -s -u "$A" "$J/job/myapp/lastBuild/consoleText" | grep -c "Groovy String interpolation" || true
(Bonus) make the script idempotent: when bootstrap.sh runs again, existing repositories, credentials and jobs should be skipped or updated instead of erroring (hint: first jcli get-job myapp check whether each exists; use update for credentials; continue when repository creation returns 409).

Acceptance checklist

Open-ended self-check (6 questions)

1. In your own words, describe the complete path of one myapp build from “Build Now” to “Finished: SUCCESS”, and identify which parts happen on the controller and which on the agent.

controller: receive trigger → queue (quiet period, blocking checks) → lightweight checkout of the Jenkinsfile and parse → submit placeholder task for the agent block → label match to agent1 → allocate executor; agent: lock workspace → checkout scm → run sh (pytest, docker build, smoke test); back on the controller: stream and save logs, copy junit results and archived files to builds/N, evaluate post conditions, write build.xml, release executor.

2. Why does an agent connecting inbound not need to expose any port? In what situations should WebSocket be used instead?

The connection is initiated by the agent: first HTTP discovery, then a connection to the controller's TCP inbound port, after which the channel is bidirectional. Use WebSocket when the controller can only expose HTTPS (for example, behind a load balancer / reverse proxy), which removes the need for port 50000.

3. An LTS user cannot see the latest version of a plugin on the plugins page — is this a bug?

No. The Update Center trims metadata by core version and only offers the highest version compatible with the current core; the newest version may require a newer weekly core (for example, the latest JUnit requires 2.589).

4. Masking already displays the token as ****; why still avoid double-quoted interpolation?

Interpolation concatenates the secret into the command string on the controller and passes it to the agent as plaintext process arguments (ps visible), and it may also appear in Pipeline's internal records; masking only handles raw text in log output. Single quotes keep the secret only as an environment variable.

5. What is the risk of mounting docker.sock on agent1 in this lesson? List two production alternatives.

Anyone who can run commands on agent1 can obtain host root through the Docker daemon. Alternatives: a dedicated build VM as the agent; rootless / isolated Docker (or a dind sidecar, which has a privileged-mode cost); daemonless image build tools; Kubernetes ephemeral Pod agents (Lesson 5).

6. When tests fail, would you make the build FAILURE or UNSTABLE? What are the consequences of each?

FAILURE: later stages are skipped and no image is produced; it is the strongest signal. UNSTABLE: the build continues (can be combined with skipStagesAfterUnstable), suitable for the case where the quality gate should not block but must be visible; however, you must ensure that artifacts from UNSTABLE builds are never released. The team should agree on one convention.

Sources and version notes

All version facts were verified on 2026-11-16 against jenkins.io, plugins.jenkins.io, updates.jenkins.io, Docker Hub, GitHub and Gitea documentation
Verification date 2026-11-16
TopicVerification resultSource (accessed 2026-11-16)
LTS versions2.580.2 (2026-10-28), 2.580.1 (2026-09-30), 2.568.3 (2026-09-02); 2.580.2 includes security fixesLTS Changelog
Weekly versions2.590 (2026-11-09), 2.589 (2026-11-01), 2.588 (2026-10-28)Weekly Changelog; updates.jenkins.io/current/latestCore.txt = 2.590
Java supportJava 25 (from LTS 2.541.1, planned end 2029-09), Java 21 (from 2.479.1, planned end 2027-09); Java 17's last LTS is 2.541.3 and last weekly is 2.544; from 2.555.1, Java 21+ is requiredJava Support Policy; LTS Changelog
2.580.x upgrade notesFrom 2.580.1, 9 split plugins are no longer bundled in the WAR (bouncycastle API, Command Agent Launcher, JDK Installer, JAXB, Trilead API, SSH server, JAF API, JavaMail API, Instance Identity); direct upgrades from 1.577 and earlier require first installing 5 plugins, including JUnit and Mailer; 2.580.2 has no additional upgrade notesUpgrade guide 2.580
Docker imagesjenkins/jenkins:2.580.2-jdk21,2.580.2-lts-jdk21,-jdk25,-slim,-alpine,-rhel-ubi9-jdk21, Windows ltsc2022/2025 all exist; latest follows weekly; the official Docker install page uses 2.580.2-jdk21; from 2.568.1 there are no Windows 2019 imagesDocker Hub jenkins/jenkins;Installing Jenkins: Docker
inbound agent imagejenkins/inbound-agent:3395.v6e5377b_0fb_3c-5-jdk21 (2026-11-12); usage -url … [-workDir=…] <secret> <agent name>; environment variables such as JENKINS_URL are now marked deprecated; prefer arguments / REMOTING_OPTSDocker Hub;README_inbound-agent
Controller isolation and executorsStrongly recommended: do not build on the built-in node; builds on the built-in node have the same filesystem access as the Jenkins process; Agent → Controller access control has always been enabled since 2.326; the node documentation recommends setting controller executors to 0; the built-in node was renamed in 2.307 / 2.319.1Controller Isolation;Using agents;Built-in node migration
Suggested plugins19 suggested plugins (platform-plugins.json: cloudbees-folder, antisamy-markup-formatter, build-timeout, credentials-binding, timestamper, ws-cleanup, ant, gradle, workflow-aggregator, github-branch-source, pipeline-github-lib, pipeline-graph-view, git, ssh-slaves, matrix-auth, ldap, email-ext, mailer, dark-theme); calculated against the 2.580.2 Update Center, 92 in total including required dependencies, which include junitplatform-plugins.json; updates.jenkins.io/update-center.actual.json?version=2.580.2
Plugin versionsThe Update Center provides for 2.580.2: workflow-aggregator 608.v67378e9d3db_1, pipeline-model-definition 2.2293.v6e7193cec599, workflow-cps 4403.v471713a_cea_19, git 5.11.0, credentials 1514.vb_01eb_014e7d4, credentials-binding 728.v902a_273b_8947, junit 1458.1460.vd53b_087eeb_2c, pipeline-graph-view 1053.v9df19e6ceed2, gitea 286.v0740a_413c1eb_, docker-workflow 653.v2f2c08eff0ec, matrix-auth 3.3, configuration-as-code 2147.v8a_8d38668c72, github-branch-source 1986.v801e40614d00, blueocean 1.27.26; on plugins.jenkins.io, the latest junit 1463.v7508416a_349c and the latest pipeline-graph-view 1134.v63b_71c6f549b_ require core 2.589plugins.jenkins.io(API); Update Center JSON
Security advisoriesMost recent: 2026-10-28 (includes core), 2026-09-16 (plugins only), 2026-09-02 (includes core), 2026-08-05 (includes core)Security Advisories
Declarative syntaxpost conditions always, changed, fixed, regression, aborted, failure, success, unstable, unsuccessful, cleanup, executed in this order; triggers only cron, pollSCM, upstream; options list (including timestamps, skipStagesAfterUnstable, disableRestartFromStage)Pipeline Syntax
Gitealatest 28.4.0 (2026-11-15); starting with 28.0 the “1.” prefix is dropped (formerly 1.28); gitea admin user create and generate-access-token --scopes parametersDocker Hub gitea/gitea;GitHub releases;Gitea CLI; the version number change comes from third-party reports (linuxiac, alternativeto); the original official blog text could not be found
Docker CLI imagedocker:29-cli exists (2026-11-16, corresponding to 29.10.0)Docker Hub docker
myapp dependenciesCarried over from the Docker course: flask 3.1.*, redis 5.*, gunicorn 23.*, python:3.13-slim; the latest pytest is 9.2.0 (PyPI), and this lesson uses pytest==9.*from Lesson 1 of the Docker course;PyPI pytest

Video verification notes

This lesson lists only videos whose titles and channels were verified via YouTube oEmbed (https://www.youtube.com/oembed?url=…&format=json) on 2026-11-16, with titles and channels verified:

oEmbed only verified titles and channels; the videos were not watched segment by segment. The content descriptions in “meta” come from titles and public course outlines and may differ in detail from the videos. Most of these videos were recorded in 2020–2023, so for version numbers, interfaces and security advice (for example, building on the controller, or the old master/slave terminology), follow this lesson. No verifiable dedicated videos were found for plugin dependencies and the Update Center, credential scope and interpolation warnings, or readiness review and troubleshooting methods; the corresponding modules state this and provide storyboard scripts instead.

Voice narration notes

The “Voice” tab uses the browser's built-in Web Speech API to read the Chinese narration script (zh-CN) and the English terms (en-US); it does not depend on the network or external scripts. This courseware cannot embed MP3 or generate video; the narration script and storyboard can be passed to a TTS or video tool to produce audio and video.

Known limitations

  • Lab commands have not been run in a real environment: this courseware was written without actually running these commands; all “expected outputs” are examples, and the hashes, IDs, timestamps, build numbers, image sizes, GIDs and Python minor versions in them are illustrative values; console and CLI output formats may differ slightly depending on plugin versions.
  • gitea admin user generate-access-token 's output format (using awk '{print $NF}' taking the last field) was written based on Gitea's existing behavior; the official documentation gives no output example. If the format differs, copy the token from the output manually. Token scope write:repository is based on Gitea's token scope naming rules and has not been tested on 28.4.
  • list-credentials,create-credentials-by-xml / update-credentials-by-xml is a CLI command provided by the Credentials plugin; the output table format is an example. The error text when the lightweight checkout cannot find the Jenkinsfile may differ slightly from the example.
  • The default value of the “Treat username as secret” option differs depending on how the credential was created and on the plugin version; this lesson makes no assertion about the default.
  • The agent image takes the files from docker:29-cli copies the docker and buildx binaries, based on the official image's directory layout; if the layout changes, you can instead install the Docker official apt repository's docker-ce-cli (the approach the official Docker install page uses for the controller).
  • DOCKER_GID is read from docker.sock's group via a temporary container; this applies to both Linux and Docker Desktop. However, the socket permission behavior of Docker Desktop may differ between versions; if you run into permission problems, see the Docker Desktop documentation.
  • The release date and version number of the next LTS baseline (after 2.580) have not been verified; refer to jenkins.io. All version numbers in this lesson are based on data as of 2026-11-16.
  • The build lifecycle animation is based on Jenkins Queue's public state model (waiting / blocked / buildable / left) and a simplified implementation of Pipeline placeholder task behavior; it does not cover throttling, locks, cloud node provisioning and similar cases (covered in Lesson 7).