Jenkins on Kubernetes: Dynamic Pod Agents, Pod Templates, Containers per Step and Running Jenkins in the Cluster
Why Pod Agents?
text
Build starts ─► Jenkins creates a POD in Kubernetes (jnlp agent + your tool containers)
─► steps run inside the pod ─► build ends ─► the pod is deleted
- Clean every time: no leftover files or tool drift
- Elastic: 50 builds at once need 50 pods, and cost nothing when idle
- Right tools per build: one container for Maven, one for Node, one for Docker builds, in the same pod
- Isolation: resource requests, limits, namespaces and network policies apply
Connect Jenkins to the Cluster
Install the Kubernetes plugin, then *Manage Jenkins, Clouds, New cloud, Kubernetes*.
| Setting | Value |
|---|---|
| Kubernetes URL | Leave empty when Jenkins runs inside the same cluster. Otherwise the API server URL |
| Kubernetes Namespace | jenkins-agents (create it and keep agents separate from other apps) |
| Credentials | A service account token or kubeconfig as a Jenkins credential, when Jenkins is outside the cluster |
| Jenkins URL | The address agents use to reach the controller (for example the internal Service name) |
| Jenkins tunnel | Only needed for TCP inbound agents. WebSocket is recommended |
| Pod Retention | Never (default) deletes pods after the build |
yaml
# RBAC so Jenkins can create agent pods in its namespace
apiVersion: v1
kind: Namespace
metadata: {name: jenkins-agents}
---
apiVersion: v1
kind: ServiceAccount
metadata: {name: jenkins, namespace: jenkins-agents}
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata: {name: jenkins-agent-manager, namespace: jenkins-agents}
rules:
- apiGroups: [""]
resources: ["pods", "pods/exec", "pods/log", "events"]
verbs: ["create", "delete", "get", "list", "patch", "update", "watch"]
- apiGroups: [""]
resources: ["secrets"]
verbs: ["get"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata: {name: jenkins-agent-manager, namespace: jenkins-agents}
subjects: [{kind: ServiceAccount, name: jenkins, namespace: jenkins-agents}]
roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: jenkins-agent-manager}
A Pod Template in the Jenkinsfile
groovy
pipeline {
agent {
kubernetes {
defaultContainer 'maven'
yaml '''
apiVersion: v1
kind: Pod
metadata:
labels: {app: ci}
spec:
serviceAccountName: jenkins-build
securityContext: {runAsUser: 1000, fsGroup: 1000}
containers:
- name: maven
image: maven:3.9-eclipse-temurin-21
command: ['sleep']
args: ['infinity']
resources:
requests: {cpu: '500m', memory: 1Gi}
limits: {memory: 2Gi}
volumeMounts:
- {name: m2cache, mountPath: /root/.m2}
- name: node
image: node:22-alpine
command: ['sleep']
args: ['infinity']
- name: trivy
image: aquasec/trivy:latest
command: ['sleep']
args: ['infinity']
volumes:
- name: m2cache
persistentVolumeClaim: {claimName: maven-cache}
'''
}
}
stages {
stage('Build') {
steps { sh 'mvn -B -DskipTests package' } // runs in defaultContainer: maven
}
stage('Frontend') {
steps {
container('node') { sh 'npm ci && npm run build' } // same pod, same workspace, other tools
}
}
stage('Scan') {
steps {
container('trivy') { sh 'trivy fs --exit-code 1 --severity CRITICAL .' }
}
}
}
}
- Every pod always has a
jnlpcontainer (the agent) added by the plugin. You list your tool containers and keep them alive withsleep infinity - All containers in the pod share the workspace volume, so files built by one are seen by another
container('name') { ... }runs steps inside a chosen container- Use
defaultContainerto avoid wrapping every step - Set requests and limits, so pods are scheduled well and cannot starve the cluster
- Put the YAML in a file in your repository (
yamlFile 'ci/pod.yaml') for readability
Reusable Pod Templates With JCasC
yaml
jenkins:
clouds:
- kubernetes:
name: "k8s"
namespace: "jenkins-agents"
jenkinsUrl: "http://jenkins.jenkins.svc.cluster.local:8080"
webSocket: true
templates:
- name: "maven"
label: "maven"
containers:
- name: "maven"
image: "maven:3.9-eclipse-temurin-21"
command: "sleep"
args: "infinity"
ttyEnabled: true
resourceRequestCpu: "500m"
resourceRequestMemory: "1Gi"
Install Jenkins on Kubernetes With Helm
bash
helm repo add jenkins https://charts.jenkins.io && helm repo update
kubectl create namespace jenkins
cat > values.yaml <<'EOF'
controller:
image:
tag: "lts-jdk21"
numExecutors: 0
jenkinsUrl: "https://jenkins.example.com/"
installPlugins:
- kubernetes
- workflow-aggregator
- git
- configuration-as-code
- credentials-binding
JCasC:
defaultConfig: true
ingress:
enabled: true
ingressClassName: nginx
hostName: jenkins.example.com
persistence:
enabled: true
size: 50Gi
storageClass: fast-ssd
agent:
enabled: false # we define pod templates in Jenkinsfiles and JCasC
EOF
helm install jenkins jenkins/jenkins -n jenkins -f values.yaml
kubectl -n jenkins get pods
kubectl -n jenkins exec svc/jenkins -c jenkins -- /bin/cat /run/secrets/additional/chart-admin-password && echo
Ingress controller: The example uses an ingress class name as a placeholder. Use the controller you actually run, because the community ingress-nginx project has been retired. Check which Ingress or Gateway API controller your cluster uses.
| Chart value | Purpose |
|---|---|
controller.numExecutors: 0 | No builds on the controller pod |
controller.installPlugins | Plugins installed at start-up |
controller.JCasC | Configuration as Code, kept in Git |
persistence | A PVC for JENKINS_HOME. Back it up. |
controller.resources | CPU and memory requests and limits |
serviceAccount | Account the controller runs as |
Caching in Pods
- A
PersistentVolumeClaimfor the Maven or npm cache (useReadWriteManystorage if several pods share it, or one PVC per team) - Use a proxy repository such as Nexus or Artifactory close to the cluster: it speeds up all builds and is easier than shared volumes
- Container image layers: use a registry cache or Kaniko
--cache=true
Troubleshooting
| Symptom | Check |
|---|---|
Waiting for next available executor and no pods | Cloud misconfigured, missing label, or no permission to create pods. Read the controller log and kubectl -n jenkins-agents get events |
Pod stays Pending | Not enough CPU or memory on nodes, or the PVC does not bind. kubectl describe pod |
| Agent cannot connect back | Wrong Jenkins URL, firewall, or WebSocket proxy settings |
ImagePullBackOff | Image name wrong or registry credentials missing (use imagePullSecrets) |
Steps hang inside container('x') | Container exited. Make sure it runs sleep infinity and not an image that quits |
Forbidden: pods is forbidden | RBAC role is missing a verb |
| Builds slow to start | Image pulls: pre-pull images with a DaemonSet, use smaller images and a local registry |
Practice Tasks
- Install the Kubernetes plugin and connect a lab cluster (kind or minikube)
- Run a pipeline with a pod template containing two tool containers
- Add resource requests and limits and a PVC cache
- Install Jenkins with the Helm chart and keep values in Git
- Cause a pod
Pendingstate by requesting too much memory, and fix it
Conclusion
The Kubernetes plugin creates a fresh pod for each build, with several tool containers sharing one workspace, and deletes it afterwards. Give the controller RBAC to create pods, define pod templates in the Jenkinsfile or JCasC, set resources and caches, and install the controller itself with the official Helm chart and a persistent volume.
Quick Summary: pod agents benefits; cloud + RBAC; yaml pod template; container(); JCasC cloud; Helm values; caching; troubleshooting.

