
·16 min read
Should I Run Jenkins in Kubernetes? Docker vs K8s Deployment Guide
Docker Compose, bare metal, or Kubernetes for the Jenkins controller, static vs dynamic agents, and the security basics I'd set up before anyone runs a build.
I've run Jenkins on bare metal, in Docker containers, on Kubernetes, and even on a Raspberry Pi (don't ask). Here's what actually works, what doesn't, and when to use each approach.
"Where should we run Jenkins?" comes up in every architecture discussion, and the answer isn't simple because Jenkins is weird. It's stateful, it spawns jobs that need their own resources, and its plugins expect filesystem access. Get the deployment wrong and you'll spend more time fighting Jenkins than using it.
Bottom line: Start with Docker Compose on a VM for small teams. Move to Kubernetes only when you need dynamic scaling. Bare metal is fine if you're okay with manual maintenance. Don't chase HA for the controller unless you really need it, the complexity usually isn't worth it.
Why Jenkins Is Awkward to Deploy
Jenkins started life as Hudson in the mid-2000s and was renamed Jenkins in 2011 after the fork from Oracle. It predates Docker (2013) and Kubernetes (2014), and it shows:
- It's stateful as hell: jobs, build history, plugins, credentials, all stored as files under
JENKINS_HOME - It wants to manage agents: it assumes it can SSH into machines or spin up new ones
- Plugin chaos: around 2,000 plugins of varying quality, with their own assumptions about the runtime
- It's a JVM: you'll be tuning heap for your workload
Jenkins works fine. But these traits make deployment strategy matter more than it does for a stateless app.
Option 1: Docker Container on a VM (My Default)
# docker-compose.yml
services:
jenkins:
image: jenkins/jenkins:lts-jdk21
container_name: jenkins
restart: unless-stopped
ports:
- "8080:8080"
- "50000:50000" # inbound (JNLP) agents
volumes:
- jenkins_home:/var/jenkins_home
- /var/run/docker.sock:/var/run/docker.sock # host Docker daemon, see the security section
environment:
- JAVA_OPTS=-Xmx2048m -Xms1024m
volumes:
jenkins_home:No version: key on purpose, Compose v2 ignores it and warns. And mounting the socket isn't Docker-in-Docker, your builds talk to the host's daemon (more on why that's dangerous below).
This is my go-to for small to medium teams. Backups are "stop, copy the volume, start", and a throwaway Jenkins to test a plugin upgrade takes seconds.
Our production controller runs like this today: Jenkins in a container on a dedicated VM. Upgrades are pull the new image and recreate the container. When disk fills up, you know exactly where to look. When something breaks, you're not debugging Kubernetes networking on top of Jenkins.
The one time it really hurt us wasn't the VM going down, it was the disk filling up (see the mistakes section). One box means one place to fill up, so retention matters more here than anywhere.
What to watch:
- The Docker socket: jobs that can reach it can take over the host
- Resource limits: set them, or Jenkins will eat all your RAM
- Backups: automate them or you'll lose everything
- No HA: VM down = Jenkins down
Option 2: Bare Metal / Plain VM
The apt-key one-liners you'll still find in old tutorials are deprecated. The current way is a keyring file plus signed-by:
# Ubuntu/Debian. Jenkins needs Java 17 or 21 installed first.
sudo apt install -y fontconfig openjdk-21-jre
# The key file name changes when Jenkins rotates its signing key.
# Check https://pkg.jenkins.io/debian-stable/ for the current one.
sudo wget -O /etc/apt/keyrings/jenkins-keyring.asc \
https://pkg.jenkins.io/debian-stable/jenkins.io-2023.key
echo "deb [signed-by=/etc/apt/keyrings/jenkins-keyring.asc] https://pkg.jenkins.io/debian-stable binary/" \
| sudo tee /etc/apt/sources.list.d/jenkins.list > /dev/null
sudo apt update
sudo apt install -y jenkins
sudo systemctl enable --now jenkinsWhen it makes sense: you already manage VMs and have no Docker/K8s in the stack, compliance doesn't allow containers, you have ancient plugins that assume host paths, or it's an existing Jenkins that has been running for years and nobody wants to touch it.
It works, but upgrades are a pain. You're managing Java versions, system packages, and plugin conflicts on one box.
The killer issue is reproducibility. When Jenkins breaks, you can't spin up an identical copy to test a fix. You're SSH'd into prod, making changes, and hoping. Over time the server becomes a unique snowflake, there's no rollback unless you took a snapshot, and moving to a new server means migrating plugins, jobs, and configs by hand.
Option 3: Controller and Agents on Kubernetes
If you do this, use the official Helm chart instead of hand-writing manifests. You get the controller StatefulSet, the Kubernetes plugin pre-wired for agent pods, and JCasC (controller.JCasC.configScripts) out of the box:
helm repo add jenkins https://charts.jenkins.io
helm repo update
helm install jenkins jenkins/jenkins -n jenkins --create-namespace -f values.yaml# values.yaml (a minimal start)
controller:
resources:
requests: { cpu: "1", memory: "2Gi" }
limits: { cpu: "2", memory: "4Gi" }
installPlugins:
- kubernetes
- workflow-aggregator
- git
- configuration-as-code
persistence:
size: 100GiPin plugin versions (kubernetes:<version>) once you're past the first install.
For reference, this is roughly what the chart's StatefulSet boils down to:
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: jenkins
spec:
serviceName: jenkins
replicas: 1
selector:
matchLabels:
app: jenkins
template:
metadata:
labels:
app: jenkins
spec:
securityContext:
fsGroup: 1000 # the image runs as uid 1000; without this a fresh PVC is often not writable
containers:
- name: jenkins
image: jenkins/jenkins:lts-jdk21
ports:
- containerPort: 8080
- containerPort: 50000
volumeMounts:
- name: jenkins-home
mountPath: /var/jenkins_home
resources:
requests:
memory: "2Gi"
cpu: "1000m"
limits:
memory: "4Gi"
cpu: "2000m"
volumeClaimTemplates:
- metadata:
name: jenkins-home
spec:
accessModes: [ "ReadWriteOnce" ]
resources:
requests:
storage: 100GiIf you hand-roll it and skip the fsGroup, the first thing you'll likely see is the controller crash-looping with a permission denied on /var/jenkins_home.
Why I Recommend This (Sometimes)
This model earns its keep once the build queue starts backing up. With Kubernetes agents, build concurrency scales with what the cluster has free. Each build gets its own pod with its own CPU/memory limits, and when it finishes the pod is gone.
The Kubernetes plugin works surprisingly well. Configure it once, and Jenkins provisions a pod per build:
// Jenkinsfile
pipeline {
agent {
kubernetes {
yaml '''
apiVersion: v1
kind: Pod
spec:
containers:
- name: maven
image: maven:3.9-eclipse-temurin-17
command: ['sleep']
args: ['infinity']
'''
}
}
stages {
stage('Build') {
steps {
container('maven') {
sh 'mvn clean package'
}
}
}
}
}The plugin adds the jnlp agent container to the pod by itself. Your containers just need to stay alive (sleep infinity) so steps can run inside them.
Common Problems
- Two layers to debug: now you're debugging Jenkins AND Kubernetes
- ReadWriteOnce storage: the controller PVC pins the pod to wherever the volume can attach
- Slow agent startup: pulling images per build adds 30-60 seconds unless images are cached on the nodes
- Plugin compatibility: some plugins assume a static agent with a persistent workspace
- Network policies: agents connect to the controller (port 50000, or 443/8080 with WebSocket). Lock down the agent namespace and forget this, and every agent pod hangs at "Waiting for agent to connect"
Is Controller HA Worth It?
Honestly, don't do this unless you have a very specific need.
Open source Jenkins has no active-active clustering. Two controllers on the same JENKINS_HOME will corrupt it, each assumes it owns those files. The best you get is active-passive, and on Kubernetes a single-replica StatefulSet already does most of that (dead pod gets rescheduled). Failover still takes minutes because Jenkins loads every job on startup, and running builds are lost anyway.
Real HA is a paid product (CloudBees CI). It makes sense when you already pay for CloudBees, downtime costs real money per minute, and someone's full-time job is keeping Jenkins up.
For everyone else: accept that Jenkins will be down during upgrades.
Static vs Dynamic Agents
Here's something nobody talks about: where you run the controller matters way less than how you run agents.
Static Agents
Jenkins Controller → SSH → Permanent Agent VMsSimple, predictable, works with every plugin. Also wasted resources, configuration drift, and manual scaling.
Our heaviest pipelines still run on a big permanent agent host, and that's exactly where drift bit us. Every deploy step did eval $(ssh-agent -s) and never killed it, so the host quietly collected thousands of orphaned ssh-agent processes over a couple of months. Another time, someone ran gh auth setup-git on the agent for a quick manual test. That wrote a credential helper into the agent user's ~/.gitconfig, git consults it before Jenkins' own credentials, and every checkout started failing with 403. Neither would survive on an agent that's thrown away after each build.
Dynamic Agents
Jenkins Controller → Kubernetes/Docker → Ephemeral AgentsScales with the cluster, no drift, you pay only while builds run. The cost is slower startup and needing decent image management.
With ephemeral agents, every build gets a fresh environment that's destroyed when done, so no state lingers between builds.
My recommendation: whatever you do with the controller, use dynamic agents. Even if Jenkins itself runs in Docker Compose, have it spin up Docker containers as agents (setup below).
Which One Should You Choose?
- Docker Compose: 1-50 developers, one VM you can dedicate, 10-30 minutes of downtime is acceptable, you're not on Kubernetes for anything else
- Kubernetes: you already run K8s and have people who can debug it, you run many concurrent builds, you need resource isolation or quotas per team
- Bare metal: you already have it and it works, compliance requires it, or you have plugins that break in containers
- HA controller: only if downtime literally costs $10k+ per hour and you're paying for CloudBees
What We Actually Run
- Controller: Jenkins in Docker on a dedicated Compute Engine VM in GCP,
JENKINS_HOMEon the VM's persistent disk - Agents: a large permanent Linux agent host for the heavy pipelines, with the drift trade-offs described above
- Pipelines: one shared library with a common pipeline template, so retention, reports and scans are fixed in one place for every service
- Access: no public SSH. Port 22 only through an IAP tunnel or the VPN
Why not run the controller on Kubernetes? Because the complexity isn't worth it for us. Troubleshooting is "SSH to one machine", startup is fast, performance is predictable on dedicated resources, and if the disk fills up you resize one disk instead of fighting a PVC. If agent capacity becomes the bottleneck, the agents are what I'd move to Kubernetes first, not the controller.
When to move more to Kubernetes: 50+ builds a day and Docker agents on one host can't keep up, per-team quotas, or many agent types (Java, Node, Python) you want as pod templates. Even then, consider moving only the agents.
Mistakes Worth Avoiding
Mistake 1: Jenkins Controller in K8s Too Early
For a small team, the overhead of StatefulSets, PVCs, and debugging pod issues isn't worth it. Put the controller on Kubernetes when you already run everything else there and have people who debug it daily, not because it's the modern thing to do.
Mistake 2: Not Planning for Disk Growth
This one is ours. The controller's 500 GB disk hit 100%, and the first symptom wasn't Jenkins at all, it was SSH. With no free space, the VM's guest agent couldn't set up login users, so every key was rejected with Permission denied (publickey). We got in through an IAP tunnel and started digging.
The cause was in our shared pipeline template. The HTML report steps (Semgrep, Trivy, Docker build logs) used the whole workspace as reportDir, so every build archived three full copies of the repo, roughly 95 MB each. There was no build discarder, and that's multiplied by every branch of every service job.
The fix, both in the shared template:
- Give each report its own small directory, so the report is the report, not the repo. Reports went from ~116 MB to under 100 KB per build.
- Add retention to the template once, so every job inherits it:
options { buildDiscarder(logRotator(numToKeepStr: '20', artifactNumToKeepStr: '10')) }
Cleaning up the old reports took the disk from about 305 GB used to under 80 GB. Lesson: du -sh $JENKINS_HOME/jobs/* before you buy a bigger disk. It's almost never "we have a lot of builds", it's one step archiving something it shouldn't.
Mistake 3: Mounting the Docker Socket Without Thinking
Mounting /var/run/docker.sock lets jobs control Docker, and that's basically root on the host. One malicious Jenkinsfile can take over the server. If builds need Docker, give them a dedicated build agent (or rootless BuildKit), not the controller's daemon.
Mistake 4: Not Using Configuration as Code
Configure Jenkins through the UI and every rebuild means remembering dozens of settings. With the Configuration as Code plugin the config lives in Git. If I had to pick one thing from this post to do tomorrow, it's this.
Securing Jenkins in Production
Jenkins security is usually an afterthought until something happens. These are the parts that matter.
Plugins
Plugins run in the same JVM as the controller. A bad or compromised plugin can read every credential and run arbitrary code, and plugin dependency conflicts (two plugins wanting different library versions) are a classic way to break an upgrade.
- Pin plugin versions: list them with versions in a
plugins.txtand install withjenkins-plugin-cliin your image build. Don't let the UI auto-update in prod. Test upgrades on a copy first. - Remove what you don't use: every plugin is attack surface. Check Manage Jenkins → Plugins → Installed every few months.
- Watch advisories: jenkins.io/security/advisories, or the
jenkinsci-advisoriesmailing list. Jenkins also shows a warning banner in the UI for vulnerable installed plugins, don't dismiss it.
Sandboxing Build Jobs
In Docker or Kubernetes deployments, jobs can often reach the Docker socket (root on the host), read secrets from env vars or mounted volumes, talk to any internal service, and eat unlimited CPU/memory. Lock the agent pod down:
apiVersion: v1
kind: Pod
metadata:
name: jenkins-agent
spec:
securityContext:
runAsNonRoot: true
runAsUser: 1000
fsGroup: 1000
seccompProfile:
type: RuntimeDefault
containers:
- name: agent
image: jenkins/inbound-agent:latest-jdk21
securityContext:
allowPrivilegeEscalation: false
capabilities:
drop:
- ALL
readOnlyRootFilesystem: true
volumeMounts:
- name: workspace # with a read-only root FS the agent needs somewhere to write
mountPath: /home/jenkins/agent
- name: tmp
mountPath: /tmp
resources:
limits:
cpu: "2"
memory: "4Gi"
requests:
cpu: "500m"
memory: "1Gi"
volumes:
- name: workspace
emptyDir: {}
- name: tmp
emptyDir: {}readOnlyRootFilesystem without the emptyDir mounts gives you agents that die on startup. Build tools writing to ~/.m2 or ~/.npm will need mounts too.
On top of that: a separate namespace per team or sensitivity level with a ResourceQuota, and gVisor or Kata Containers if you build untrusted code.
Secrets
Poor secrets handling is the most common Jenkins security failure. Don't put secrets in job configs or Jenkinsfiles, don't echo them, and don't share one admin account across teams.
One thing people miss: the built-in credentials store is encrypted, but the key lives next to the data in $JENKINS_HOME/secrets/. Whoever has a copy of your jenkins_home backup has every credential. Treat backups like secrets.
Bind credentials only where they're needed, and pull from an external secret manager where you can:
pipeline {
agent any
stages {
stage('Deploy') {
steps {
// AWS Credentials plugin
withCredentials([aws(credentialsId: 'aws-prod-deployer',
accessKeyVariable: 'AWS_ACCESS_KEY_ID',
secretKeyVariable: 'AWS_SECRET_ACCESS_KEY')]) {
sh 'aws s3 cp build.zip s3://artifacts/'
}
// HashiCorp Vault plugin
withVault(vaultSecrets: [[path: 'secret/database',
secretValues: [[envVar: 'DB_PASSWORD', vaultKey: 'password']]]]) {
sh './migrate.sh'
}
}
}
}
}Use single quotes in sh steps so the shell expands the variable, not Groovy. With double quotes Groovy interpolates the secret into the command string and Jenkins warns about it in the build log.
Bound credentials are masked in the console log, but masking is string matching. A secret that gets base64'd or split in your script leaks anyway.
Network Policies
In Kubernetes, agent pods usually have far more network access than they need. A starting point for the agent namespace:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: jenkins-agent-policy
namespace: jenkins-agents
spec:
podSelector:
matchLabels:
jenkins/jenkins-jenkins-agent: "true" # label the Helm chart puts on agent pods; check yours
policyTypes:
- Ingress
- Egress
ingress: [] # nothing needs to connect in to an agent
egress:
# DNS
- to:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: kube-system
ports:
- protocol: UDP
port: 53
- protocol: TCP
port: 53
# Agents connect to the controller (HTTP + inbound agent port)
- to:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: jenkins
ports:
- protocol: TCP
port: 8080
- protocol: TCP
port: 50000
# HTTPS out for dependencies, but not the cloud metadata endpoint
- to:
- ipBlock:
cidr: 0.0.0.0/0
except:
- 169.254.169.254/32
ports:
- protocol: TCP
port: 443Namespaces don't have a name label by default, use kubernetes.io/metadata.name. Blocking the metadata endpoint only works through ipBlock.except, and on GKE/EKS use Workload Identity / IRSA so there's nothing worth stealing there anyway.
Outside the cluster: put the controller UI behind VPN or the corporate network, never straight on the internet.
Access Control
The "logged-in users can do anything" default is fine for a lab, not for an org. With the matrix-auth plugin and JCasC (this is the entries format from matrix-auth 3.x; the older flat "Overall/Read:group" strings are deprecated):
jenkins:
authorizationStrategy:
projectMatrix:
entries:
- group:
name: "jenkins-admins"
permissions:
- "Overall/Administer"
- group:
name: "developers"
permissions:
- "Overall/Read"
- "Job/Read"
- "Job/Build"
- "Job/Cancel"
- group:
name: "auditors"
permissions:
- "Overall/Read"
- "Job/Read"Anonymous gets nothing because it's not listed. Use folders to scope job permissions per team, SSO via SAML/OIDC (LDAP is acceptable), the Audit Trail plugin to see who changed what, and keep developers away from production deploy jobs.
Alternatives to Mounting the Docker Socket
- Rootless Docker (
dockerd-rootless-setuptool.sh install): the daemon runs as a normal user, so escaping to it doesn't give you host root. - Kaniko: builds images from a Dockerfile without a daemon. Heads-up: Google archived the original
GoogleContainerTools/kanikorepo in 2025. It still works, but check whether you want to move to a maintained fork or to BuildKit before building new pipelines on it. - Buildah / Podman: rootless builds without privileged access.
The Kaniko pattern on Kubernetes agents looks like this (it also needs registry credentials mounted at /kaniko/.docker/config.json to push):
pipeline {
agent {
kubernetes {
yaml '''
apiVersion: v1
kind: Pod
spec:
containers:
- name: kaniko
image: gcr.io/kaniko-project/executor:debug
command: ["/busybox/cat"]
tty: true
'''
}
}
stages {
stage('Build Image') {
steps {
container('kaniko') {
sh '''
/kaniko/executor \\
--context=dir://$WORKSPACE \\
--destination=myrepo/myapp:${BUILD_NUMBER}
'''
}
}
}
}
}Note the :debug tag. The plain executor image has no shell or busybox, so /busybox/cat and the sh step won't work with :latest.
Quick Start: Docker Compose With Docker Agents
If you're starting fresh today, here's what I'd do.
Step 1: An Image With Your Plugins
The stock image ships with no plugins, and with the setup wizard disabled nothing installs them. No plugin, no JCasC. Bake them in:
# Dockerfile
FROM jenkins/jenkins:lts-jdk21
RUN jenkins-plugin-cli --plugins \
configuration-as-code \
docker-plugin \
matrix-auth \
workflow-aggregator \
gitStep 2: Docker Compose
services:
jenkins:
build: .
container_name: jenkins
restart: unless-stopped
user: root # needed for Docker socket access; the trade-off is covered in the security section
ports:
- "8080:8080"
- "50000:50000"
volumes:
- jenkins_home:/var/jenkins_home
- /var/run/docker.sock:/var/run/docker.sock
- ./casc.yaml:/var/jenkins_home/casc.yaml:ro
environment:
- JAVA_OPTS=-Xmx2048m -Xms1024m -Djenkins.install.runSetupWizard=false
- CASC_JENKINS_CONFIG=/var/jenkins_home/casc.yaml
- JENKINS_ADMIN_PASSWORD # passed through from your shell
volumes:
jenkins_home:Exporting JENKINS_ADMIN_PASSWORD on the host isn't enough, Compose only passes it into the container if it's listed.
Step 3: Configuration as Code
# casc.yaml
jenkins:
systemMessage: "Jenkins configured automatically"
numExecutors: 0 # controller doesn't run builds
securityRealm:
local:
allowsSignup: false
users:
- id: admin
password: ${JENKINS_ADMIN_PASSWORD}
authorizationStrategy:
globalMatrix:
entries:
- user:
name: "admin"
permissions:
- "Overall/Administer"
- group:
name: "authenticated"
permissions:
- "Overall/Read"
clouds:
- docker:
name: "docker"
dockerApi:
dockerHost:
uri: "unix:///var/run/docker.sock"
templates:
- labelString: "docker-agent"
dockerTemplateBase:
image: "jenkins/agent:latest-jdk21"
mounts:
- "type=bind,source=/var/run/docker.sock,destination=/var/run/docker.sock"
remoteFs: "/home/jenkins/agent"
connector:
attach:
user: "root"
instanceCapStr: "10"The "attach" connector wants jenkins/agent, not jenkins/inbound-agent (that one dials in over port 50000). The Docker plugin's CasC takes mounts as --mount strings, not a volumes list. And the agent gets the host socket too, so the Docker-socket warning applies to every build.
Step 4: Launch It
export JENKINS_ADMIN_PASSWORD='something-better-than-changeme'
docker compose up -d --buildThat's it. Jenkins with dynamic Docker agents in about 5 minutes. Point a pipeline at agent { label 'docker-agent' } to use them.
TL;DR
The best Jenkins deployment is the one you can actually maintain. Docker Compose for the controller, dynamic agents (Docker or K8s) for builds. Kubernetes for everything only if you're already deep in K8s and have the people for it. Bare metal if you hate yourself or have strict compliance requirements. Skip HA unless downtime actually costs you serious money.
Jenkins being down for upgrades once a month is not a real problem for most teams. Spending a week debugging PVC issues in Kubernetes is.
A note on how this was written: I used AI to help with phrasing and structure. The tone, the opinions, the war stories, the code, and everything else here are mine.