Jenkins CI/CD Mastery: Complete Automation Guide
· Pavan Y N · cicd, devops, docker, kubernetes
Jenkins is an open-source automation server written in Java that builds, tests, and deploys software. It is widely used for CI/CD (continuous integration and continuous delivery), and the plugin catalog lists more than 2,000 plugins. EduGeek explains the parts of Jenkins that matter in production: how to run it, how to write Declarative and Scripted Pipelines, how to share pipeline code, which plugins to trust, and how to troubleshoot the problems that show up most often.
The examples were written against the Jenkins LTS (long-term support) line 2.580.x, released in September 2026. Jenkins 2.555.1 and later require Java 21 or Java 25, and Java 17 is no longer supported (its last LTS release was 2.541.3 in March 2026).
# What is Jenkins?
Jenkins is a controller-and-agent system. The controller hosts the web UI, the REST API, the job scheduler, the build queue, and the plugin manager. Agents are the machines or containers that actually run builds.
## Key features
- →Extensible: more than 2,000 plugins integrate Jenkins with source control, build tools, clouds, and notification systems.
- →Distributed: builds run on agents, which can be static machines, containers, or Kubernetes pods created on demand.
- →Pipeline as code: a
Jenkinsfilestored next to the application code defines the pipeline. - →Configuration as code: the Configuration as Code (JCasC) plugin describes the controller itself in YAML.
- →Open source: free, with a large community and a public security process.
## Jenkins architecture
┌─────────────────────────────────────────┐
│ Jenkins controller │
│ ┌──────────────────────────────────┐ │
│ │ Web UI and API │ │
│ ├──────────────────────────────────┤ │
│ │ Job scheduler and build queue │ │
│ ├──────────────────────────────────┤ │
│ │ Plugin manager │ │
│ └──────────────────────────────────┘ │
└─────────────┬───────────────────────────┘
│
┌─────────┴─────────┬─────────────┐
│ │ │
┌───▼────┐ ┌───────▼──┐ ┌──────▼───┐
│ Agent 1│ │ Agent 2 │ │ Agent 3 │
│ (Linux)│ │ (Windows)│ │ (K8s pod)│
└────────┘ └──────────┘ └──────────┘
The controller should not run builds itself. Builds on the built-in node run with the same file system access as the Jenkins process, so the Jenkins security documentation advises setting the built-in node's executor count to 0 and running all builds on agents.
# Installation and setup
## Quick start with Docker
The official jenkins/jenkins image ships the current LTS release. Pin a Java variant such as lts-jdk21 so an image update never changes the JVM unexpectedly.
docker run -d --name jenkins \
-p 8080:8080 -p 50000:50000 \
-v jenkins_home:/var/jenkins_home \
jenkins/jenkins:lts-jdk21
# Read the initial admin password for the setup wizard
docker exec jenkins cat /var/jenkins_home/secrets/initialAdminPassword
Port 8080 serves the web UI. Port 50000 is only needed by inbound agents that connect over TCP; agents that use WebSocket connect over the normal HTTP(S) port instead.
Avoid the common shortcut of mounting /var/run/docker.sock into the controller and running it as root with privileged: true. That hands the Jenkins process control of the host's Docker daemon, which is root-equivalent. Keep the controller unprivileged and let Docker-capable agents run the container builds.
## Reproducible setup with a Dockerfile and Docker Compose
JCasC configures Jenkins but does not install plugins, so bake the plugins into the image with jenkins-plugin-cli.
# Dockerfile
FROM jenkins/jenkins:lts-jdk21
ENV JAVA_OPTS="-Djenkins.install.runSetupWizard=false"
ENV CASC_JENKINS_CONFIG=/usr/share/jenkins/casc/casc.yaml
COPY plugins.txt /usr/share/jenkins/ref/plugins.txt
RUN jenkins-plugin-cli --plugin-file /usr/share/jenkins/ref/plugins.txt
COPY casc.yaml /usr/share/jenkins/casc/casc.yaml
# plugins.txt
configuration-as-code
matrix-auth
workflow-aggregator
git
credentials-binding
# compose.yaml
services:
jenkins:
build: .
ports:
- "8080:8080"
- "50000:50000"
volumes:
- jenkins_home:/var/jenkins_home
environment:
ADMIN_PASSWORD: ${ADMIN_PASSWORD}
GITHUB_USERNAME: ${GITHUB_USERNAME}
GITHUB_TOKEN: ${GITHUB_TOKEN}
DOCKER_TOKEN: ${DOCKER_TOKEN}
restart: unless-stopped
volumes:
jenkins_home:
Current Docker Compose does not need a top-level version: key. Put the four secret values in an untracked .env file or in a secret store, never in the repository.
## Configuration as Code
This casc.yaml creates a local admin user, restricts anonymous access, sets the controller to zero executors, and defines two credentials. The matrix authorization strategy needs the matrix-auth plugin, which is why it appears in plugins.txt.
# casc.yaml
jenkins:
systemMessage: "Configured by Jenkins Configuration as Code"
numExecutors: 0
scmCheckoutRetryCount: 3
securityRealm:
local:
allowsSignup: false
users:
- id: "admin"
password: "${ADMIN_PASSWORD}"
authorizationStrategy:
globalMatrix:
entries:
- user:
name: "admin"
permissions:
- "Overall/Administer"
- group:
name: "authenticated"
permissions:
- "Overall/Read"
credentials:
system:
domainCredentials:
- credentials:
- usernamePassword:
scope: GLOBAL
id: "github-credentials"
username: "${GITHUB_USERNAME}"
password: "${GITHUB_TOKEN}"
- string:
scope: GLOBAL
id: "docker-registry-token"
secret: "${DOCKER_TOKEN}"
unclassified:
location:
url: "http://localhost:8080/"
adminAddress: "admin@example.com"
The older permissions: list under globalMatrix is a deprecated attribute that logs a warning when loaded; the current form is entries: with user: and group: items. Cloud and agent definitions are best added from the Docker or Kubernetes plugin documentation, because they depend on how agents will connect.
Add agents after the controller is running. An inbound agent started with docker run --init jenkins/inbound-agent -url http://<controller>:8080 <secret> <agent-name> connects over TCP by default, and WebSocket mode avoids opening port 50000.
# Jenkins Pipeline fundamentals
A Pipeline is defined in a Jenkinsfile. Jenkins supports two syntaxes: Declarative (structured, validated before the run starts) and Scripted (full Groovy, more flexible). The Jenkins documentation presents Declarative first and labels Scripted as advanced, and Declarative is the better default.
## Declarative Pipeline
pipeline {
agent any
options {
timeout(time: 30, unit: 'MINUTES')
timestamps()
disableConcurrentBuilds()
}
environment {
APP_NAME = 'my-application'
}
stages {
stage('Build') {
steps {
sh 'npm ci'
sh 'npm run build'
}
}
stage('Test') {
steps {
sh 'npm test'
}
}
}
post {
success {
echo 'Pipeline succeeded.'
}
failure {
echo 'Pipeline failed.'
}
cleanup {
cleanWs()
}
}
}
When the Jenkinsfile comes from source control (a Multibranch Pipeline or "Pipeline script from SCM"), Declarative Pipeline checks out the repository automatically. A separate git or checkout scm step is only needed after skipDefaultCheckout(). The cleanWs() step comes from the Workspace Cleanup plugin.
## Scripted Pipeline
node('docker') {
def registry = 'registry.example.com'
def appName = 'my-application'
def app
stage('Checkout') {
checkout scm
}
stage('Build') {
app = docker.build("${registry}/${appName}:${env.BUILD_NUMBER}")
}
stage('Test') {
app.inside {
sh 'npm test'
}
}
stage('Push') {
docker.withRegistry("https://${registry}", 'docker-credentials') {
app.push()
}
}
stage('Deploy') {
withCredentials([file(credentialsId: 'kubeconfig', variable: 'KUBECONFIG')]) {
sh "kubectl set image deployment/${appName} ${appName}=${registry}/${appName}:${env.BUILD_NUMBER}"
sh "kubectl rollout status deployment/${appName} --timeout=5m"
}
}
}
docker.build, inside, and withRegistry come from the Docker Pipeline plugin. The second argument of withRegistry is the ID of a username/password credential stored in Jenkins.
# Advanced Pipeline patterns
## Multibranch Pipeline
A Multibranch Pipeline creates one job per branch or pull request found in the repository, and it sets BRANCH_NAME automatically, so there is no need to derive it from GIT_BRANCH. Sanitize the name before using it in a Docker tag, because branch names such as feature/login contain characters that Docker tags do not allow.
pipeline {
agent any
environment {
REGISTRY = 'registry.example.com'
APP_NAME = 'my-application'
IMAGE_TAG = "${BRANCH_NAME.replaceAll('[^A-Za-z0-9_.-]', '-')}-${BUILD_NUMBER}"
}
stages {
stage('Build') {
steps {
sh 'docker build -t $REGISTRY/$APP_NAME:$IMAGE_TAG .'
}
}
stage('Security scan') {
steps {
sh 'trivy image --severity HIGH,CRITICAL --exit-code 1 $REGISTRY/$APP_NAME:$IMAGE_TAG'
}
}
stage('Deploy to staging') {
when { branch 'develop' }
steps {
echo 'Deploy to the staging namespace here.'
}
}
stage('Deploy to production') {
when { branch 'main' }
steps {
echo 'Deploy to the production namespace here.'
}
}
}
}
The branch condition only works in a Multibranch Pipeline. The shell commands use single quotes so that the shell, not Groovy, expands the variables. The Trivy scanner is a separate binary that must be installed on the agent.
## Parallel execution
Run independent checks in parallel and stop the others as soon as one fails with failFast. reuseNode true mounts the current workspace into the container, so every branch sees the checked-out source; without it each Docker agent gets a fresh workspace.
pipeline {
agent any
stages {
stage('Checks') {
failFast true
parallel {
stage('Unit tests') {
agent {
docker {
image 'node:24-alpine'
reuseNode true
}
}
steps {
sh 'npm ci && npm run test:unit'
}
}
stage('Integration tests') {
agent {
docker {
image 'node:24-alpine'
reuseNode true
}
}
steps {
sh 'npm ci && npm run test:integration'
}
}
stage('Dependency audit') {
agent {
docker {
image 'node:24-alpine'
reuseNode true
}
}
steps {
sh 'npm audit --audit-level=high'
}
}
}
}
}
}
The docker agent type requires the Docker Pipeline plugin and a Docker daemon on the agent. Node.js 22 and 24 are the supported long-term-support lines at the time of writing; Node.js 18, 20, and 21 have reached end of life, so the examples no longer use them.
## Matrix builds
A matrix block expands axes into a grid of parallel cells. Axis values are available as variables inside the cell, including in the agent directive. Variables defined in the cell's own environment block are not: building the image name in environment and reading it in agent fails at run time with No such property. Compute the value directly from the axes instead.
pipeline {
agent none
stages {
stage('Build and test') {
matrix {
agent {
docker {
image "node:${NODE_VERSION}-${VARIANT}"
}
}
axes {
axis {
name 'NODE_VERSION'
values '22', '24'
}
axis {
name 'VARIANT'
values 'alpine', 'slim'
}
}
excludes {
exclude {
axis {
name 'NODE_VERSION'
values '22'
}
axis {
name 'VARIANT'
values 'slim'
}
}
}
stages {
stage('Build') {
steps {
sh 'node --version'
sh 'npm ci'
sh 'npm run build'
}
}
stage('Test') {
steps {
sh 'npm test'
}
}
}
}
}
}
}
This produces three cells (22 with alpine, 24 with alpine, 24 with slim). Matrix cells that need different operating systems should select agents with labels, for example agent { label "${PLATFORM}-agent" }, which is the pattern in the Jenkins syntax reference.
## Shared libraries
A shared library keeps reusable pipeline code in its own repository. The directory layout is vars/ for global variables (steps), src/ for Groovy classes, and resources/ for files loaded with libraryResource.
// vars/buildDockerImage.groovy
def call(Map config) {
def imageName = config.imageName ?: error('imageName is required')
def imageTag = config.imageTag ?: env.BUILD_NUMBER
def dockerfile = config.dockerfile ?: 'Dockerfile'
def context = config.context ?: '.'
def fullName = "${imageName}:${imageTag}"
sh "docker build -f ${dockerfile} -t ${fullName} ${context}"
return fullName
}
@Library('my-shared-library@main') _
pipeline {
agent any
stages {
stage('Build') {
steps {
script {
env.IMAGE = buildDockerImage(
imageName: 'registry.example.com/my-application',
imageTag: env.BUILD_NUMBER
)
}
}
}
}
}
The _ after @Library is a placeholder for the annotation when only global variables are needed, and @main pins a branch, tag, or commit. Pin to a tag for production pipelines. Libraries configured globally are "trusted" and can call any Jenkins or Java API, so anyone who can push to that repository effectively has unlimited access to Jenkins; folder-level libraries run in the Groovy sandbox. See the advanced Jenkins guide for a larger library with deployment helpers and approval gates.
# Jenkins plugins
Every plugin adds attack surface and upgrade work, so install only what a pipeline needs. The plugin catalog lists the status of each one, and unmaintained plugins should be replaced.
| Area | Plugins to know |
|---|---|
| Pipeline | Pipeline (workflow-aggregator), Pipeline Graph View, Pipeline: Stage View, Pipeline: Multibranch |
| Source control | Git, GitHub Branch Source, GitLab Branch Source, Bitbucket |
| Build tools | Maven Integration, Gradle, NodeJS, Docker Pipeline |
| Agents and deployment | Kubernetes, Docker, Pipeline: AWS Steps |
| Quality and security | SonarQube Scanner, OWASP Dependency-Check, Checkmarx |
| Notifications | Slack Notification, Email Extension |
| Observability | Prometheus metrics, OpenTelemetry |
| Controller management | Configuration as Code, Matrix Authorization Strategy, Credentials Binding |
Two plugins deserve a warning. Blue Ocean is deprecated and receives only selected security and defect fixes; the Jenkins project points to Pipeline Graph View and Pipeline: Stage View for pipeline visualization. And the standalone Terraform plugin that older guides mention has not had a release since 2020, so run Terraform from a pipeline step instead of relying on it.
## Slack notifications
pipeline {
agent any
stages {
stage('Build') {
steps {
sh 'npm run build'
}
}
}
post {
success {
slackSend(
color: 'good',
message: "Build succeeded: ${env.JOB_NAME} #${env.BUILD_NUMBER}",
channel: '#deployments',
tokenCredentialId: 'slack-token'
)
}
failure {
slackSend(
color: 'danger',
message: "Build failed: ${env.JOB_NAME} #${env.BUILD_NUMBER}\n${env.BUILD_URL}",
channel: '#deployments',
tokenCredentialId: 'slack-token'
)
}
}
}
## SonarQube analysis and quality gate
withSonarQubeEnv injects the server URL and the authentication token from the global SonarQube configuration, so the pipeline never handles the token itself. Avoid copying the token into a variable and passing it as -Dsonar.login through a double-quoted sh string. That leaks the secret through Groovy interpolation, which the Jenkins documentation says should never be used with credentials.
pipeline {
agent any
stages {
stage('Code analysis') {
steps {
script {
scannerHome = tool 'SonarQubeScanner'
}
withSonarQubeEnv('SonarQube') {
sh "${scannerHome}/bin/sonar-scanner -Dsonar.projectKey=my-application -Dsonar.sources=src"
}
}
}
stage('Quality gate') {
steps {
timeout(time: 5, unit: 'MINUTES') {
waitForQualityGate abortPipeline: true
}
}
}
}
}
waitForQualityGate needs a SonarQube webhook that calls back to Jenkins so the pipeline can pause until the server finishes computing the gate.
# Operating Jenkins safely
The practices below follow the Jenkins documentation and project security guidance.
- →Patch the controller and plugins on a schedule. The Jenkins project publishes security advisories for both core and plugins at jenkins.io/security/advisories, with an RSS feed. Track the LTS line, and update plugins at the same cadence.
- →Keep builds off the controller. Set the built-in node to zero executors, as the JCasC file above does, and use agents.
- →Prefer ephemeral agents. A Kubernetes or Docker agent that exists only for one build avoids stale workspaces and leaked state.
- →Treat credentials as bindings. Use
withCredentialsor thecredentials()helper, and use single-quotedshstrings so the shell reads secrets from its environment. - →Back up
JENKINS_HOME, and keep configuration in code. JCasC plus aplugins.txtfile lets the controller be rebuilt from Git. - →Make pipelines, not jobs. A
Jenkinsfilein the repository gets code review, history, and branch-specific behavior for free.
# Common issues and troubleshooting
## Pipeline hangs
Set timeouts at the pipeline and stage level so a stuck step fails instead of holding an executor.
pipeline {
agent any
options {
timeout(time: 1, unit: 'HOURS')
timestamps()
}
stages {
stage('Build') {
options {
timeout(time: 10, unit: 'MINUTES')
}
steps {
sh 'npm run build'
}
}
stage('Flaky test') {
steps {
retry(3) {
sh 'npm test'
}
}
}
}
}
Retrying hides real defects when used for everything, so use retry only around steps with known transient failures, such as network calls.
## Out-of-memory errors
Java heap errors make the controller unresponsive. Give the JVM an explicit heap, or let it size itself from the container limit.
# Explicit heap
docker run -e JAVA_OPTS="-Xmx4g -Xms2g" jenkins/jenkins:lts-jdk21
# Or a percentage of the container memory limit
docker run -m 6g -e JAVA_OPTS="-XX:MaxRAMPercentage=75" jenkins/jenkins:lts-jdk21
The first line of defense is keeping builds off the controller, because heavy builds compete with it for CPU and memory. Inside pipelines, disableConcurrentBuilds() and a post { cleanup { cleanWs() } } block prevent runaway workspace growth.
## Agent connection problems
If agents show as offline, work through these checks:
- •Read the agent log. For a container agent, run
docker logs <agent-container>. - •Confirm the secret and agent name match what the controller shows on the node's page.
- •For TCP agents, confirm the controller's inbound agent port is reachable from the agent. For agents behind a proxy or in another network, switch to WebSocket mode, which connects over the controller's normal HTTP(S) port.
- •Make sure the controller's Jenkins URL (Manage Jenkins, System) is set to an address that agents can resolve.
For Kubernetes agents, the plugin injects JENKINS_URL, JENKINS_SECRET, and the agent name into the pod and runs the agent in a container named jnlp by default, built from jenkins/inbound-agent when you do not specify one. A minimal pod template therefore needs no args:
pipeline {
agent {
kubernetes {
yaml '''
apiVersion: v1
kind: Pod
spec:
containers:
- name: node
image: node:24-alpine
command: ["sleep"]
args: ["99d"]
'''
}
}
stages {
stage('Build') {
steps {
container('node') {
sh 'npm ci && npm run build'
}
}
}
}
}
## Credential problems
stage('Push image') {
steps {
withCredentials([
usernamePassword(
credentialsId: 'docker-credentials',
usernameVariable: 'DOCKER_USER',
passwordVariable: 'DOCKER_PASS'
)
]) {
sh '''
echo "$DOCKER_PASS" | docker login -u "$DOCKER_USER" --password-stdin
docker push registry.example.com/my-application:latest
'''
}
}
}
stage('Deploy to server') {
steps {
sshagent(credentials: ['ssh-credentials']) {
sh 'ssh deploy@server.example.com "bash -s" < deploy.sh'
}
}
}
If a credential cannot be found, check its ID, its scope (a folder-scoped credential is invisible to jobs outside that folder), and whether the credential type matches the binding that was used.
# Best practices
## Pipeline design
- →Keep pipelines short and readable, and prefer Declarative syntax.
- →Give stages meaningful names and set timeouts.
- →Move repeated logic into a shared library, and pin the library version.
## Performance
- →Run independent work in parallel and use
failFast. - →Cache dependencies with a mounted volume or a build cache rather than reinstalling on every run.
- →Clean workspaces and limit concurrent builds.
## Security
- →Store secrets in the Jenkins credentials store or an external secret manager, never in a
Jenkinsfile. - →Use least-privilege service accounts and restrict who can configure trusted libraries.
- →Require an approval step before production deployments. The advanced Jenkins guide shows the
inputdirective.
## Delivery to Kubernetes
Jenkins builds and tests well, but a pipeline that runs kubectl against production gives the CI server cluster credentials. Many teams instead have Jenkins build the image and commit the new tag to a config repository, and let an in-cluster tool apply it. The GitOps guide covers that pull-based model, and Git version control mastery covers the branching side.
# Key takeaways
- →Run Jenkins LTS 2.580.x or newer on Java 21 or Java 25, because Java 17 is no longer supported by current releases.
- →Build the controller image with
jenkins-plugin-cliand configure it with Configuration as Code, using theentries:form for matrix authorization rather than the deprecatedpermissions:list. - →Set the built-in node to zero executors and run builds on ephemeral agents, and never mount the Docker socket into the controller.
- →In Declarative matrix builds, compute values for the
agentdirective from the axes, because variables from the cell'senvironmentblock are not available when the agent is selected. - →Never interpolate credentials into double-quoted
shstrings, and letwithSonarQubeEnv,withCredentials, orcredentials()hand secrets to the shell through its environment. - →Blue Ocean is deprecated, so use Pipeline Graph View or Pipeline: Stage View, and replace unmaintained plugins instead of keeping them installed.
- →Subscribe to the Jenkins security advisories and update the controller and plugins on a regular schedule.
# Further reading
Test yourself: Jenkins CI/CD Mastery assessment