← Full reference

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:

ObjectWhen to use it
Deploymenta stateless service (web, API): N identical interchangeable pods, smooth rollout of a new version
StatefulSeta stateful service (databases, queues): each pod has a stable name name-0, name-1 and its own disk
DaemonSetexactly one pod on every node: log and monitoring agents, network plugins
Joba one-off task that must complete successfully: a migration, an import
CronJoba 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:

FieldMeaningDefault / notes
namecontainer name, unique within the podrequired
imageimage: nginx:1.27, registry.example.com/app:2.1without a tag, :latest is used
imagePullPolicyAlways / IfNotPresent / NeverAlways for :latest and untagged images, otherwise IfNotPresent
commanda list: replaces the image's ENTRYPOINTif unset — taken from the image
argsa list: replaces the image's CMD$(VAR) substitutes a container environment variable
workingDirworking directoryfrom the image
ports[].containerPortthe port the app listens oninformational: the port is reachable without it too; name gives the port a name for Services and probes
env, envFromenvironment variablessee k8s-config
volumeMountswhere to mount the pod's volumessee k8s-config
resourcesCPU and memory requests / limitssee k8s-probes-resources
livenessProbe, readinessProbe, startupProbehealth checkssee k8s-probes-resources
securityContextrunAsUser, runAsNonRoot, readOnlyRootFilesystem, allowPrivilegeEscalation, capabilities

Pod: pod level

Fields of the pod spec (in controllers — spec.template.spec):

FieldMeaningDefault / notes
containersmain containers, started at the same timerequired, at least one
initContainersrun one by one before the main ones; each must exit with code 0if one fails, the pod reruns them (according to restartPolicy)
initContainers[].restartPolicy: Alwayssidecar: starts in init-container order, but isn't waited on to finish and runs alongside the main containersstable since Kubernetes 1.33, enabled by default since 1.29
restartPolicyAlways / OnFailure / Never — whether to restart failed containersAlways; Deployment/StatefulSet/DaemonSet allow only Always, Job only OnFailure or Never
serviceAccountNamewhich identity the pod uses for the APIdefault; see k8s-rbac
volumesvolumes shared by the pod's containerssee k8s-config
nodeSelectorrun only on nodes with these labels: {disktype: ssd}
tolerationsallow nodes with "repelling" taints
affinitynodeAffinity, podAntiAffinity — flexible placement rules
imagePullSecrets[{name: secret}] — access to a private registrya secret of type kubernetes.io/dockerconfigjson
terminationGracePeriodSecondshow long to wait after SIGTERM before SIGKILL30
hostNetworkuse the node's networkfalse
securityContextfor the whole pod: runAsUser, fsGroup, …

Deployment

FieldMeaningDefault / notes
spec.replicashow many pods to keep1
spec.selector.matchLabelslabels by which the Deployment finds its podsrequired; immutable after creation
spec.selector.matchExpressions[{key, operator: In|NotIn|Exists|DoesNotExist, values}]
spec.template.metadata.labelspod labelsmust match the selector
spec.strategy.typeRollingUpdate — replace one by one / Recreate — kill all old ones firstRollingUpdate
spec.strategy.rollingUpdate.maxSurgehow many pods may run above replicas during a rollout (a number or %)25% (rounded up)
spec.strategy.rollingUpdate.maxUnavailablehow many pods may be unavailable during a rollout25% (rounded down); can't be 0 together with maxSurge
spec.minReadySecondshow long a pod must be Ready to count as available0
spec.revisionHistoryLimithow many old ReplicaSets to keep for rollback10
spec.progressDeadlineSecondsafter how many seconds without progress the rollout counts as stuck600
spec.pausedpause the rolloutfalse

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

FieldMeaningDefault / notes
spec.serviceNamename of the headless service (clusterIP: None) that gives pods DNS namesrequired in the 1.32 schema; you create the Service itself separately
spec.replicas, spec.selector, spec.templateas in a Deployment
spec.volumeClaimTemplatesPVC templates: each pod gets its own diskthe PVC is named <template>-<statefulset>-<number>, e.g. data-db-0
spec.podManagementPolicyOrderedReady — pods one at a time, in order / Parallel — all at onceOrderedReady
spec.updateStrategy.typeRollingUpdate (from the highest number down to zero) / OnDelete (only a pod deleted by hand gets updated)RollingUpdate
spec.updateStrategy.rollingUpdate.partitionupdate only pods with number ≥ N (canary rollout)0
spec.persistentVolumeClaimRetentionPolicywhenDeleted / whenScaled: Retain or Deleteboth 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

FieldMeaningDefault / notes
spec.selector, spec.templateas in a Deploymentthere's no replicas field
spec.template.spec.nodeSelector / affinitywhich nodes to run onwithout them — on all suitable nodes
spec.template.spec.tolerationsneeded to land on nodes with taints (e.g. control-plane)
spec.updateStrategy.typeRollingUpdate / OnDeleteRollingUpdate, maxUnavailable: 1

Job

FieldMeaningDefault / notes
spec.completionshow many successful completions are needed1
spec.parallelismhow many pods run at the same time1
spec.backoffLimithow many failed attempts before the Job is marked failed6; pauses between attempts grow: 10 s, 20 s, 40 s… up to 6 min
spec.activeDeadlineSecondsoverall time limit; when it expires the pods are killed and the Job is Failedno limit
spec.ttlSecondsAfterFinisheddelete the Job and its pods N seconds after it finishesnot deleted
spec.completionModeNonIndexed / Indexed — each pod gets a number in JOB_COMPLETION_INDEXNonIndexed
spec.suspenddon't create pods while truefalse
spec.template.spec.restartPolicyNever — a new pod on failure / OnFailure — restart the container in the same podyou must set one of the two

Don't write a selector for a Job: Kubernetes generates it itself.

CronJob

FieldMeaningDefault / notes
spec.schedulecron-format schedule: '*/15 * * * *', '0 3 * * 1', @hourly, @dailyrequired; see cron
spec.timeZonetime zone: Europe/Berlinthe kube-controller-manager's zone, usually UTC
spec.jobTemplate.specthe Job description (all fields from the table above)required
spec.concurrencyPolicyAllow — run in parallel / Forbid — skip a run while the previous one is running / Replace — kill the previous one and start a new oneAllow
spec.startingDeadlineSecondshow late a run may start; later — the run is skippedno limit
spec.successfulJobsHistoryLimithow many successful Jobs to keep3
spec.failedJobsHistoryLimithow many failed Jobs to keep1
spec.suspendpause the schedulefalse

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), but kubeconform lets it through — it checks only the structure. Check label matching by eye.
  • The selector can'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 the selector alone.
  • restartPolicy: Always in a Job isn't accepted by the API server (it needs Never or OnFailure), but the schema doesn't catch it: kubeconform says valid.
  • command replaces the ENTRYPOINT entirely. Set command: ["--debug"] and Kubernetes tries to run a file named --debug. Put arguments for the image's default command in args.
  • command: ["sh", "-c", "a && b"] — the whole shell string goes as one element. command: ["sh", "-c", "echo", "hi"] prints an empty line: hi becomes $0, not an argument to echo.
  • Indentation in containers. - name: and image: must be at the same level. A shifted image turns into a field of another object or a parse error.
  • :latest and imagePullPolicy. With :latest the image is pulled on every pod start, and an untagged image also means :latest. For reproducibility specify an exact tag.
  • maxSurge: 0 and maxUnavailable: 0 at the same time are forbidden: the rollout has no room to move.
  • replicas in the manifest and an HPA. If a HorizontalPodAutoscaler manages the replicas, every kubectl apply with replicas: 2 resets them back. Remove replicas from the manifest (see k8s-probes-resources).
  • A StatefulSet doesn't create the Service from serviceName — you have to define it separately, with clusterIP: None.
  • StatefulSet disks remain after deletion and after reducing replicas: PVCs from volumeClaimTemplates aren't deleted by default. This protects the data, but is also a source of "orphaned" volumes.
  • CronJob and the time zone. Without timeZone the 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: Allow by default. If a job runs longer than the interval, runs overlap. For backups and migrations set Forbid.
  • An init container that never exits keeps the pod in Init:0/1 forever. 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