Kubernetes: Pod, Deployment, StatefulSet, DaemonSet, Job, CronJob
Workload manifests — containers, init and sidecar containers, replicas, rollout strategies, jobs
A workload is an object that runs containers. A container always lives inside a pod: the smallest unit; containers in one pod share an IP and volumes. Pods are rarely created by hand — controllers spawn them:
| Object | When to use it |
|---|---|
| Deployment | a stateless service (web, API): N identical interchangeable pods, smooth rollout of a new version |
| StatefulSet | a stateful service (databases, queues): each pod has a stable name name-0, name-1 and its own disk |
| DaemonSet | exactly one pod on every node: log and monitoring agents, network plugins |
| Job | a one-off task that must complete successfully: a migration, an import |
| CronJob | a Job on a schedule: backups, cleanup |
The pod description is the same for all of them and lives in spec.template (for CronJob — in spec.jobTemplate.spec.template).
Syntax
apiVersion: apps/v1 # Pod — v1, Deployment/StatefulSet/DaemonSet — apps/v1, Job/CronJob — batch/v1
kind: Deployment
metadata:
name: web
labels: {app: web}
spec:
replicas: 2
selector:
matchLabels: {app: web} # which pods the controller manages
template: # the pod template
metadata:
labels: {app: web} # must match the selector
spec:
containers:
- name: web
image: nginx:1.27
ports:
- containerPort: 80
It's easier to generate a skeleton than to type it: kubectl create deployment|job|cronjob … --dry-run=client -o yaml (see kubectl). There's no offline generator for Pod, StatefulSet and DaemonSet: kubectl run needs a cluster, and StatefulSet and DaemonSet are easy to make from a generated Deployment.
Pod: containers
Fields of a spec.containers[] (and initContainers[]) element:
| Field | Meaning | Default / notes |
|---|---|---|
name | container name, unique within the pod | required |
image | image: nginx:1.27, registry.example.com/app:2.1 | without a tag, :latest is used |
imagePullPolicy | Always / IfNotPresent / Never | Always for :latest and untagged images, otherwise IfNotPresent |
command | a list: replaces the image's ENTRYPOINT | if unset — taken from the image |
args | a list: replaces the image's CMD | $(VAR) substitutes a container environment variable |
workingDir | working directory | from the image |
ports[].containerPort | the port the app listens on | informational: the port is reachable without it too; name gives the port a name for Services and probes |
env, envFrom | environment variables | see k8s-config |
volumeMounts | where to mount the pod's volumes | see k8s-config |
resources | CPU and memory requests / limits | see k8s-probes-resources |
livenessProbe, readinessProbe, startupProbe | health checks | see k8s-probes-resources |
securityContext | runAsUser, runAsNonRoot, readOnlyRootFilesystem, allowPrivilegeEscalation, capabilities |
Pod: pod level
Fields of the pod spec (in controllers — spec.template.spec):
| Field | Meaning | Default / notes |
|---|---|---|
containers | main containers, started at the same time | required, at least one |
initContainers | run one by one before the main ones; each must exit with code 0 | if one fails, the pod reruns them (according to restartPolicy) |
initContainers[].restartPolicy: Always | sidecar: starts in init-container order, but isn't waited on to finish and runs alongside the main containers | stable since Kubernetes 1.33, enabled by default since 1.29 |
restartPolicy | Always / OnFailure / Never — whether to restart failed containers | Always; Deployment/StatefulSet/DaemonSet allow only Always, Job only OnFailure or Never |
serviceAccountName | which identity the pod uses for the API | default; see k8s-rbac |
volumes | volumes shared by the pod's containers | see k8s-config |
nodeSelector | run only on nodes with these labels: {disktype: ssd} | |
tolerations | allow nodes with "repelling" taints | |
affinity | nodeAffinity, podAntiAffinity — flexible placement rules | |
imagePullSecrets | [{name: secret}] — access to a private registry | a secret of type kubernetes.io/dockerconfigjson |
terminationGracePeriodSeconds | how long to wait after SIGTERM before SIGKILL | 30 |
hostNetwork | use the node's network | false |
securityContext | for the whole pod: runAsUser, fsGroup, … |
Deployment
| Field | Meaning | Default / notes |
|---|---|---|
spec.replicas | how many pods to keep | 1 |
spec.selector.matchLabels | labels by which the Deployment finds its pods | required; immutable after creation |
spec.selector.matchExpressions | [{key, operator: In|NotIn|Exists|DoesNotExist, values}] | |
spec.template.metadata.labels | pod labels | must match the selector |
spec.strategy.type | RollingUpdate — replace one by one / Recreate — kill all old ones first | RollingUpdate |
spec.strategy.rollingUpdate.maxSurge | how many pods may run above replicas during a rollout (a number or %) | 25% (rounded up) |
spec.strategy.rollingUpdate.maxUnavailable | how many pods may be unavailable during a rollout | 25% (rounded down); can't be 0 together with maxSurge |
spec.minReadySeconds | how long a pod must be Ready to count as available | 0 |
spec.revisionHistoryLimit | how many old ReplicaSets to keep for rollback | 10 |
spec.progressDeadlineSeconds | after how many seconds without progress the rollout counts as stuck | 600 |
spec.paused | pause the rollout | false |
A Deployment manages pods through ReplicaSets: each template version has its own ReplicaSet, and a rollback (kubectl rollout undo) brings back the previous one. A new rollout starts on any change to spec.template — the image, variables, pod labels; changing replicas doesn't trigger a rollout.
StatefulSet
| Field | Meaning | Default / notes |
|---|---|---|
spec.serviceName | name of the headless service (clusterIP: None) that gives pods DNS names | required in the 1.32 schema; you create the Service itself separately |
spec.replicas, spec.selector, spec.template | as in a Deployment | |
spec.volumeClaimTemplates | PVC templates: each pod gets its own disk | the PVC is named <template>-<statefulset>-<number>, e.g. data-db-0 |
spec.podManagementPolicy | OrderedReady — pods one at a time, in order / Parallel — all at once | OrderedReady |
spec.updateStrategy.type | RollingUpdate (from the highest number down to zero) / OnDelete (only a pod deleted by hand gets updated) | RollingUpdate |
spec.updateStrategy.rollingUpdate.partition | update only pods with number ≥ N (canary rollout) | 0 |
spec.persistentVolumeClaimRetentionPolicy | whenDeleted / whenScaled: Retain or Delete | both Retain: disks are not deleted |
Pods get the names db-0, db-1, … and DNS names db-0.<serviceName>.<namespace>.svc.cluster.local. A pod with the same number gets the same name and the same PVC after being recreated.
DaemonSet
| Field | Meaning | Default / notes |
|---|---|---|
spec.selector, spec.template | as in a Deployment | there's no replicas field |
spec.template.spec.nodeSelector / affinity | which nodes to run on | without them — on all suitable nodes |
spec.template.spec.tolerations | needed to land on nodes with taints (e.g. control-plane) | |
spec.updateStrategy.type | RollingUpdate / OnDelete | RollingUpdate, maxUnavailable: 1 |
Job
| Field | Meaning | Default / notes |
|---|---|---|
spec.completions | how many successful completions are needed | 1 |
spec.parallelism | how many pods run at the same time | 1 |
spec.backoffLimit | how many failed attempts before the Job is marked failed | 6; pauses between attempts grow: 10 s, 20 s, 40 s… up to 6 min |
spec.activeDeadlineSeconds | overall time limit; when it expires the pods are killed and the Job is Failed | no limit |
spec.ttlSecondsAfterFinished | delete the Job and its pods N seconds after it finishes | not deleted |
spec.completionMode | NonIndexed / Indexed — each pod gets a number in JOB_COMPLETION_INDEX | NonIndexed |
spec.suspend | don't create pods while true | false |
spec.template.spec.restartPolicy | Never — a new pod on failure / OnFailure — restart the container in the same pod | you must set one of the two |
Don't write a selector for a Job: Kubernetes generates it itself.
CronJob
| Field | Meaning | Default / notes |
|---|---|---|
spec.schedule | cron-format schedule: '*/15 * * * *', '0 3 * * 1', @hourly, @daily | required; see cron |
spec.timeZone | time zone: Europe/Berlin | the kube-controller-manager's zone, usually UTC |
spec.jobTemplate.spec | the Job description (all fields from the table above) | required |
spec.concurrencyPolicy | Allow — run in parallel / Forbid — skip a run while the previous one is running / Replace — kill the previous one and start a new one | Allow |
spec.startingDeadlineSeconds | how late a run may start; later — the run is skipped | no limit |
spec.successfulJobsHistoryLimit | how many successful Jobs to keep | 3 |
spec.failedJobsHistoryLimit | how many failed Jobs to keep | 1 |
spec.suspend | pause the schedule | false |
Examples
# manifest skeletons without a cluster
kubectl create deployment web --image=nginx:1.27 --replicas=3 --port=80 \
--dry-run=client -o yaml > deploy.yaml
kubectl create job migrate --image=busybox:1.36 \
--dry-run=client -o yaml -- sh -c 'echo migrating' > job.yaml
kubectl create cronjob cleanup --image=busybox:1.36 --schedule='0 3 * * *' \
--restart=OnFailure --dry-run=client -o yaml -- sh -c 'echo cleanup' > cron.yaml
# refine with yq: rollout strategy and Job parameters
yq -i '.spec.strategy = {"type": "RollingUpdate", "rollingUpdate": {"maxSurge": 1, "maxUnavailable": 0}}' deploy.yaml
yq -i '.spec.backoffLimit = 2 | .spec.ttlSecondsAfterFinished = 600' job.yaml
yq -i '.spec.concurrencyPolicy = "Forbid" | .spec.timeZone = "Europe/Berlin"' cron.yaml
# a DaemonSet from a Deployment: change kind, remove replicas, strategy and status
# (a DaemonSet's status is different — with an empty status: {} the schema fails)
kubectl create deployment node-agent --image=busybox:1.36 --dry-run=client -o yaml -- sleep infinity \
| yq '.kind = "DaemonSet" | del(.spec.replicas) | del(.spec.strategy) | del(.status)' > ds.yaml
# validate everything against the schemas
kubeconform -strict -summary deploy.yaml job.yaml cron.yaml ds.yaml
# one field — see what you got
yq '.spec.jobTemplate.spec.template.spec.restartPolicy' cron.yaml
# in a real cluster (won't work here):
# kubectl apply -f deploy.yaml
# kubectl rollout status deploy/web
# kubectl get pods -l app=web
# kubectl create job manual-run --from=cronjob/cleanup
A pod with an init container and a sidecar:
apiVersion: v1
kind: Pod
metadata:
name: app
labels: {app: app}
spec:
initContainers:
- name: wait-db # a regular init: waits and exits
image: busybox:1.36
command: ["sh", "-c", "until nc -z db 5432; do sleep 2; done"]
- name: log-shipper # sidecar: runs for the pod's whole lifetime
image: busybox:1.36
restartPolicy: Always
command: ["sh", "-c", "tail -F /logs/app.log"]
volumeMounts:
- {name: logs, mountPath: /logs}
containers:
- name: app
image: registry.example.com/app:1.4.2
command: ["/app/server"] # instead of the image's ENTRYPOINT
args: ["--port", "8080"] # instead of the image's CMD
ports:
- {name: http, containerPort: 8080}
volumeMounts:
- {name: logs, mountPath: /var/log/app}
volumes:
- name: logs
emptyDir: {}
A StatefulSet with a headless service and its own disk for each pod:
apiVersion: v1
kind: Service
metadata:
name: db
spec:
clusterIP: None # headless: DNS names db-0.db, db-1.db
selector: {app: db}
ports:
- {name: pg, port: 5432}
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: db
spec:
serviceName: db
replicas: 2
selector:
matchLabels: {app: db}
template:
metadata:
labels: {app: db}
spec:
containers:
- name: postgres
image: postgres:16
ports:
- {name: pg, containerPort: 5432}
volumeMounts:
- {name: data, mountPath: /var/lib/postgresql/data}
volumeClaimTemplates: # PVCs data-db-0, data-db-1
- metadata:
name: data
spec:
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 1Gi
A Job that processes 10 parts, 3 at a time:
apiVersion: batch/v1
kind: Job
metadata:
name: batch
spec:
completions: 10
parallelism: 3
completionMode: Indexed # the part number is in $JOB_COMPLETION_INDEX
backoffLimit: 4
activeDeadlineSeconds: 3600
template:
spec:
restartPolicy: Never
containers:
- name: worker
image: busybox:1.36
command: ["sh", "-c", "echo part $JOB_COMPLETION_INDEX"]
Pitfalls
- The selector and pod labels don't match. For a Deployment the API server rejects such a manifest (
selector does not match template labels), butkubeconformlets it through — it checks only the structure. Check label matching by eye. - The
selectorcan't be changed on an existing Deployment, StatefulSet or DaemonSet: only deleted and recreated. When changing labels, add new ones to the pod template and leave theselectoralone. restartPolicy: Alwaysin a Job isn't accepted by the API server (it needsNeverorOnFailure), but the schema doesn't catch it:kubeconformsaysvalid.commandreplaces the ENTRYPOINT entirely. Setcommand: ["--debug"]and Kubernetes tries to run a file named--debug. Put arguments for the image's default command inargs.command: ["sh", "-c", "a && b"]— the whole shell string goes as one element.command: ["sh", "-c", "echo", "hi"]prints an empty line:hibecomes$0, not an argument toecho.- Indentation in
containers.- name:andimage:must be at the same level. A shiftedimageturns into a field of another object or a parse error. :latestandimagePullPolicy. With:latestthe image is pulled on every pod start, and an untagged image also means:latest. For reproducibility specify an exact tag.maxSurge: 0andmaxUnavailable: 0at the same time are forbidden: the rollout has no room to move.replicasin the manifest and an HPA. If a HorizontalPodAutoscaler manages the replicas, everykubectl applywithreplicas: 2resets them back. Removereplicasfrom the manifest (see k8s-probes-resources).- A StatefulSet doesn't create the Service from
serviceName— you have to define it separately, withclusterIP: None. - StatefulSet disks remain after deletion and after reducing
replicas: PVCs fromvolumeClaimTemplatesaren't deleted by default. This protects the data, but is also a source of "orphaned" volumes. - CronJob and the time zone. Without
timeZonethe schedule is evaluated in the controller's zone, usually UTC:0 3 * * *is 03:00 UTC, i.e. 05:00 in Berlin in summer. concurrencyPolicy: Allowby default. If a job runs longer than the interval, runs overlap. For backups and migrations setForbid.- An init container that never exits keeps the pod in
Init:0/1forever. Make a long-lived helper container a sidecar (restartPolicy: Always) or a regular container.
See also
kubectl · kubeconform · yq · k8s-networking · k8s-config · k8s-probes-resources · k8s-rbac · cron · docker-compose