Jenkins on Kubernetes: Dynamic Pod Agents, Pod Templates, Containers per Step and Running Jenkins in the Cluster

CI CD Pipelines with Jenkins 45 min min read Updated: Nov 17, 2026 Advanced
Jenkins on Kubernetes: Dynamic Pod Agents, Pod Templates, Containers per Step and Running Jenkins in the Cluster
Advanced Topic 3 of 3

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*.

SettingValue
Kubernetes URLLeave empty when Jenkins runs inside the same cluster. Otherwise the API server URL
Kubernetes Namespacejenkins-agents (create it and keep agents separate from other apps)
CredentialsA service account token or kubeconfig as a Jenkins credential, when Jenkins is outside the cluster
Jenkins URLThe address agents use to reach the controller (for example the internal Service name)
Jenkins tunnelOnly needed for TCP inbound agents. WebSocket is recommended
Pod RetentionNever (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 jnlp container (the agent) added by the plugin. You list your tool containers and keep them alive with sleep 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 defaultContainer to 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 valuePurpose
controller.numExecutors: 0No builds on the controller pod
controller.installPluginsPlugins installed at start-up
controller.JCasCConfiguration as Code, kept in Git
persistenceA PVC for JENKINS_HOME. Back it up.
controller.resourcesCPU and memory requests and limits
serviceAccountAccount the controller runs as

Caching in Pods

  • A PersistentVolumeClaim for the Maven or npm cache (use ReadWriteMany storage 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

SymptomCheck
Waiting for next available executor and no podsCloud misconfigured, missing label, or no permission to create pods. Read the controller log and kubectl -n jenkins-agents get events
Pod stays PendingNot enough CPU or memory on nodes, or the PVC does not bind. kubectl describe pod
Agent cannot connect backWrong Jenkins URL, firewall, or WebSocket proxy settings
ImagePullBackOffImage 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 forbiddenRBAC role is missing a verb
Builds slow to startImage pulls: pre-pull images with a DaemonSet, use smaller images and a local registry

Practice Tasks

  1. Install the Kubernetes plugin and connect a lab cluster (kind or minikube)
  2. Run a pipeline with a pod template containing two tool containers
  3. Add resource requests and limits and a PVC cache
  4. Install Jenkins with the Helm chart and keep values in Git
  5. Cause a pod Pending state 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.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators