Kubernetes Workloads: Pods, Probes, Deployments, StatefulSets, DaemonSets, Jobs, Rollouts
"Pods are the smallest deployable units of computing that you can create and manage in Kubernetes." — Kubernetes documentation, Pods (concepts/workloads/pods), checked against Kubernetes v1.37
Summary: Everything you run on Kubernetes ends up as Pods, and almost nobody should create Pods by hand: a controller (Deployment, StatefulSet, DaemonSet, Job, CronJob) keeps the right Pods alive, replaces them on change and removes them on failure, while the kubelet on each node starts their containers, probes them and stops them with a signal and a deadline. Getting a service to roll out without errors is mostly about four contracts: the probes the application answers, the termination budget it respects, the selector that ties objects together, and the update strategy of its controller. Focus: Pod anatomy (app containers, init containers, sidecar containers as restartable init containers, ephemeral containers and kubectl debug, the shared network and IPC namespace, volumes as a preview), the Pod lifecycle (Pod phases Pending Running Succeeded Failed Unknown, container states, Pod conditions, readiness gates), restartPolicy and CrashLoopBackOff, the three probes (liveness probe, readiness probe, startup probe) with their four mechanisms (exec probe, httpGet probe, tcpSocket probe, grpc probe) and every knob (initialDelaySeconds, periodSeconds, timeoutSeconds, failureThreshold, successThreshold), graceful termination (preStop hook, terminationGracePeriodSeconds, SIGTERM then SIGKILL, the endpoint removal race), resource requests and limits as a preview, labels, selectors and matchLabels (and why the selector is immutable), imagePullPolicy and image tags vs digests, ReplicaSet and Deployment (RollingUpdate and Recreate, maxSurge, maxUnavailable, minReadySeconds, progressDeadlineSeconds, revisionHistoryLimit, rollout status, rollout undo, pause and resume), StatefulSet (stable network identity, ordinal index, volumeClaimTemplates, headless Service, podManagementPolicy, partition), DaemonSet with node selectors and tolerations as a preview, Job (completions, parallelism, backoffLimit, activeDeadlineSeconds, ttlSecondsAfterFinished, indexed Job, podFailurePolicy), CronJob (schedule, concurrencyPolicy, startingDeadlineSeconds, missed runs), PodDisruptionBudget, HorizontalPodAutoscaler and Pod topology spread as previews, Services as the consumer of readiness, and the worked examples: a Go service with health endpoints and graceful shutdown, and Laravel as a php-fpm + Nginx Deployment, a queue worker Deployment, a scheduler (CronJob or schedule:work) and a migration Job. Learning goal: Write the manifests for a stateless Go service, a Laravel web tier, its workers, its scheduler and its batch jobs so that a rollout, a node drain and a crash all happen without dropped requests or duplicated work; read kubectl get, describe and rollout status output and say which controller or probe is responsible; and choose between Deployment, StatefulSet, DaemonSet, Job and CronJob for any process you are handed.
This chapter is the second in the Kubernetes group, after Kubernetes Architecture & Setup, which owns the control plane, the kubelet, the API server, etcd, container runtimes and how a cluster is installed; here those components appear only as the actors in a Pod's life. Requests, limits, QoS, scheduling, affinity, taints and autoscaling in depth are Resources, Scheduling & Autoscaling; ConfigMaps, Secrets and PersistentVolumes are Config, Secrets & Storage; securityContext, Pod Security Standards and RBAC are Kubernetes Security; templating these manifests per environment is Packaging for Kubernetes; blue-green, canary and progressive delivery on top of Deployments are Deployment Strategies; events, logs and debugging workflows are Kubernetes Observability & Troubleshooting. The images used here (distroless Go, php-fpm and Nginx targets) are built in Images & Dockerfiles; signals, PID 1 and signal.NotifyContext in Go are in OS Processes, Signals & Graceful Shutdown; Services, kube-proxy, DNS and Ingress are Kubernetes Networking; the architectural view of why an organisation runs Kubernetes is Containers & Kubernetes.
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in three tables | Everything in one minute |
| Why controllers manage Pods instead of you | Why it exists |
| Sidecars, Job failure policies, sleep hooks: which version | Where it comes from |
| Containers, shared network and IPC, volumes | Pod anatomy |
Init containers, sidecar containers, ephemeral containers, kubectl debug | Init, Sidecars, Ephemeral |
| Pending, Running, Succeeded, Failed, Unknown; Waiting/Running/Terminated | Phases and container states |
restartPolicy, backoff, CrashLoopBackOff | Restart policy |
| Liveness, readiness, startup probes and their knobs | Probes, Mechanisms, Knobs |
| preStop, grace period, SIGTERM, SIGKILL, endpoint removal | Graceful termination |
| Readiness gates, Pod conditions | Readiness gates |
| Requests and limits (preview) | Resources |
Labels, selectors, matchLabels, immutable selector | Labels and selectors |
imagePullPolicy, :latest, digests | Images |
| ReplicaSet, Deployment, RollingUpdate, Recreate | ReplicaSet, Deployment |
rollout status, undo, pause, resume, revisions | Rollouts |
| StatefulSet, headless Service, ordinals, partitions, databases | StatefulSet |
| DaemonSet, node selectors, tolerations | DaemonSet |
Job, indexed Job, podFailurePolicy, CronJob | Job, CronJob |
| PodDisruptionBudget, drains | PDB |
| HorizontalPodAutoscaler and topology spread (previews) | HPA and spread |
| How a Service uses readiness | Services |
| php-fpm + Nginx: sidecar or two containers | PHP Pods |
| Controller loops, rollout arithmetic, kubelet stop sequence, knobs, errors | Mechanics |
| Code | Go, Laravel |
| Twelve classic problems and their fixes | Solving the classic problems |
| Which controller, which probe, which strategy, which scheduler model | Choosing |
| From one Pod to many clusters | In architecture |
| Commands with real or expected output | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The workload controllers (all apps/v1 or batch/v1, Kubernetes v1.37).
| Controller | Runs | Identity of its Pods | Update strategies | Typical use |
|---|---|---|---|---|
| Deployment (via ReplicaSets) | N interchangeable Pods, forever | Random suffix (orders-api-7d4b9c-x2kq), new name on every replacement | RollingUpdate (default), Recreate | Stateless HTTP/gRPC services, workers, the Laravel web tier |
| ReplicaSet | N Pods matching a selector | Random suffix | None of its own (Deployment drives it) | Never directly; "we recommend using Deployments instead" |
| StatefulSet | N Pods with ordinals 0..N-1 | Stable name, DNS record and volume per ordinal (web-0) | RollingUpdate (default, highest ordinal first, partition), OnDelete | Databases, brokers, anything with per-member state |
| DaemonSet | One Pod per (selected) node | One per node | RollingUpdate (default), OnDelete | Log and metrics agents, CNI and storage daemons |
| Job | Pods until N succeed | Random, or an index 0..N-1 (Indexed) | Not updated: create a new Job | Migrations, exports, one-off batch work |
| CronJob | A Job per schedule tick | Per Job | Changes apply to the next Job | Nightly reports, the Laravel scheduler |
The three probes (the kubelet runs them; defaults from the probe reference).
| Probe | Question it answers | On failure | Runs | Trap |
|---|---|---|---|---|
startupProbe | "Has the app finished starting?" | Container killed and restarted per restartPolicy | Only until the first success; holds back the other two | Too few attempts for a slow boot: restart loop before the app ever starts |
livenessProbe | "Is this process wedged beyond repair?" | Container killed and restarted | For the container's whole life | Checking the database: one outage restarts every replica |
readinessProbe | "Should this Pod receive traffic now?" | Pod condition Ready=False, endpoint removed from Services | For the container's whole life | None defined: Pod receives traffic as soon as the process starts |
| Defaults | initialDelaySeconds 0, periodSeconds 10, timeoutSeconds 1, failureThreshold 3, successThreshold 1 | successThreshold must be 1 for liveness and startup |
Graceful termination in one table (what happens when a Pod is deleted).
| Moment | Actor | What happens | Your knob |
|---|---|---|---|
| t = 0 | API server | Pod gets a deletion timestamp and a grace period; kubectl shows Terminating | terminationGracePeriodSeconds (default 30) |
| t = 0, in parallel | EndpointSlice controller, then kube-proxy, Ingress, cloud LBs | Endpoint becomes ready: false, terminating: true; the traffic layer catches up over the next seconds | A delay before the app stops accepting (preStop sleep) |
| t = 0 | kubelet | Runs the preStop hook, if any, inside the grace period | lifecycle.preStop (exec, httpGet, sleep) |
| after preStop | container runtime | Sends SIGTERM (or the image's STOPSIGNAL) to PID 1 of each container | Handle the signal: stop accepting, drain, exit |
| t = grace | container runtime | SIGKILL to anything still running; Pod object removed | Keep preStop + drain below the grace period |
| sidecars | kubelet | Native sidecars get their stop signal only after the app containers have exited, in reverse order | Put helpers that must outlive the app in initContainers with restartPolicy: Always |
Why it exists
A container runtime can start a container; it cannot decide that three copies should always exist, that a new version should replace the old one a Pod at a time, or that a node that vanished took two copies with it. Before orchestration, that work was a deploy script plus a process supervisor on each host (systemd, Supervisor for Laravel's queue:work, a cron line for schedule:run), and a load balancer someone edited by hand. Kubernetes splits it into small control loops: you write the desired state as an object, a controller compares it with the observed state and creates or deletes Pods, the scheduler places each Pod on a node, and the kubelet on that node makes the containers match the Pod spec.
The Pod is the unit because some containers belong together: they share one network namespace (so localhost works between them), can share volumes and are scheduled, started and stopped as one. Controllers exist because a Pod itself is mortal: a given Pod, identified by its UID, is never moved to a different node; instead, in the docs' words, "that Pod can be replaced by a new, near-identical Pod". Whatever must survive a replacement (a name, a disk, a place in an order) has to be modelled by the controller, which is why there are several.
| Simpler choice | Richer choice | What you buy | What you pay |
|---|---|---|---|
| A bare Pod | A Deployment | Replacement on failure, rolling updates, rollback | Labels and selectors to get right |
| No probes | Startup + liveness + readiness | No traffic before ready, restarts of wedged processes | Endpoints to implement; misconfigured probes cause outages |
| SIGKILL on stop | preStop delay + SIGTERM drain | Zero dropped requests on rollout and scale-down | A termination budget to respect |
| Deployment for a database | StatefulSet (or an operator) | Stable names, one volume per member, ordered changes | Slower rollouts, manual repair in some failure modes |
| Cron on a VM | CronJob | Scheduled work with history, deadlines and concurrency rules | "Approximately once": jobs must be idempotent |
| Hope during node maintenance | PodDisruptionBudget | Drains that never take too many replicas | A budget that can block drains if set too strictly |
The analogy used through this page: a delivery company. A Pod is one van with its crew: the driver (app container) and a navigator (sidecar) share the cab, the radio and the cargo space (network namespace and volumes), and they leave and return together. Before the shift, a loader (init container) packs the van and goes home. The dispatcher (Deployment) is told "keep six vans on the road"; when a van breaks down, it sends a new one with a new number plate, and when the company changes the van model, it swaps vans one or two at a time so deliveries never stop. Some vans are special: the armoured van for the bank (StatefulSet) always has the same plate and the same safe bolted inside, so a replacement gets that plate and that safe. Every depot has exactly one fuel attendant (DaemonSet). A courier job "deliver these 8 parcels" (Job) ends when all 8 are delivered; the morning newspaper run (CronJob) starts at 5:00 every day. The supervisor checks each van: "is the engine running at all?" (liveness), "is it loaded and ready to take an order?" (readiness), "has it finished its morning checks?" (startup). At the end of a shift the van is first taken off the order board, then finishes the deliveries it has, and is towed away only if it is still out when the depot closes (SIGTERM, drain, SIGKILL).
Three common misunderstandings, up front
- "A liveness probe should check the database." If the database is down, every replica fails liveness at once and the kubelet restarts all of them, which helps nothing and adds a thundering herd when the database returns. The probe docs warn that incorrect liveness probes "can lead to cascading failures". Dependencies belong in readiness; liveness answers only "is this process able to make progress". See Probes.
- "SIGTERM arrives after the Pod has been removed from the load balancer." Removal and SIGTERM start at the same moment, in parallel: "At the same time as the kubelet is starting graceful shutdown of the Pod, the control plane evaluates whether to remove that shutting-down Pod from EndpointSlice objects". An app that closes its listener on SIGTERM drops the requests still in flight from proxies that have not caught up. See Graceful termination.
- "Changing
replicasor a label on the Deployment creates a new revision." A rollout is triggered "if and only if the Deployment's Pod template (that is,.spec.template) is changed"; scaling does not create a revision, and the selector cannot be changed at all after creation. See Deployment and Labels and selectors.
Where it comes from
| When | What happened | Source |
|---|---|---|
| v1.14 | Pod readiness gates (readinessGates) stable | Pod lifecycle docs, feature state |
| v1.21 | CronJob stable; PodDisruptionBudget policy/v1 stable | CronJob and configure-PDB docs |
| v1.24 | Indexed Jobs stable (completionMode: Indexed) | Job docs |
| v1.25 | Ephemeral containers stable (kubectl debug) | Ephemeral containers docs |
| v1.27 | gRPC probes stable; CronJob timeZone stable; deleted Pods move to a terminal phase before deletion | GRPCContainerProbe and CronJobTimeZone gates, Pod lifecycle docs |
| v1.28 | Native sidecar containers arrive as alpha ("Kubernetes v1.28: Introducing native sidecar containers", 25 Aug 2023); probe-level terminationGracePeriodSeconds stable | Kubernetes blog, probe docs |
| v1.29 | SidecarContainers beta and on by default ("the feature is active by default since Kubernetes v1.29") | Sidecar docs, feature gate |
| 13 Aug 2024, v1.31 | Pod failure policy for Jobs GA; PDB unhealthyPodEvictionPolicy GA; StatefulSet start ordinal GA | v1.31 release blog, feature gates |
| v1.32 | StatefulSet PVC auto-deletion (persistentVolumeClaimRetentionPolicy) GA; CronJobs stamp batch.kubernetes.io/cronjob-scheduled-timestamp | Feature gate, CronJob docs |
| 23 Apr 2025, v1.33 | Sidecar containers stable ("Sidecar containers graduate to stable"); Job backoffLimitPerIndex and successPolicy GA | v1.33 release blog, Job GA posts |
| v1.34 | preStop / postStart sleep action GA; Job podReplacementPolicy GA | PodLifecycleSleepAction, JobPodReplacementPolicy gates |
| v1.37 (patch 1.37.2, 13 Oct 2026) | PodReadyToStartContainers condition stable; HPA scale-to-zero beta; StatefulSet maxUnavailable beta and on by default | Releases page, feature gates |
Two lineages meet here. The Pod and the ReplicationController came first; ReplicaSet replaced the ReplicationController with set-based selectors, and Deployment was added on top so that an update creates a new ReplicaSet and scales the two against each other, which is why every Deployment Pod carries a pod-template-hash label. The other lineage is the sidecar: for years "sidecar" meant "a second entry in containers", with no start or stop ordering, which broke Jobs (the sidecar never exited, so the Job never completed) and termination (the proxy died before the app). The native sidecar, an init container with restartPolicy: Always, gives the pattern a lifecycle: started before the app, stopped after it, ignored when deciding whether a Job is complete.
The concept catalogue
Each block follows the same order: plain words, the common misunderstanding, the definition, a sequence, real scenarios, how the tools treat it, and the fix.
Pod anatomy: containers, shared network and IPC, volumes preview Must-know
In plain words: A Pod is one or more containers that Kubernetes always places on the same node and starts and stops together. They share one IP address and port space and can share directories.
Common misunderstanding: "A Pod is a container." A Pod is a sandbox (its own network namespace, created before any of your containers) plus the containers in it. Two containers in one Pod are two processes on the same "logical host"; two Pods are two hosts, even on the same node.
Definition: The Pod docs: a Pod is "a group of one or more containers, with shared storage and network resources, and a specification for how to run the containers". Networking: "Every container in a Pod shares the network namespace, including the IP address and network ports", they "can find each other via localhost" and "can also communicate with each other using standard inter-process communications like SystemV semaphores or POSIX shared memory", while containers in different Pods "can not communicate by OS-level IPC without special configuration". Volumes declared in spec.volumes are mounted per container with volumeMounts; an emptyDir lives exactly as long as the Pod (same UID). The spec holds four kinds of container in three fields: initContainers (regular init containers and native sidecars), containers (app containers) and ephemeralContainers (added only through the API for debugging).
kubectl apply -f deployment.yaml (one orders-api Pod)
1 API server stores the Pod; scheduler binds it to node-7 (PodScheduled)
2 kubelet on node-7 asks the runtime (containerd via CRI) for a sandbox: network namespace, IP 10.1.7.23
3 volumes mounted (PodReadyToStartContainers = True)
4 init containers run in order; native sidecars start and keep running (Initialized = True)
5 images pulled per imagePullPolicy; app containers started in the same network namespace
6 probes start; readiness true on every container -> ContainersReady, Ready = TrueReal scenarios:
- Nginx and php-fpm in one Pod talk over
127.0.0.1:9000; in Docker Compose the same config saidapp:9000(a DNS name), which does not exist inside a Pod. - Two containers both try to listen on 8080: the second fails with "address already in use", because the port space is shared.
- A log shipper reads the app's files from a shared
emptyDir; after a Pod replacement the directory is empty again. - A Go service and an Envoy proxy share the Pod IP, so the Service targets the proxy port and the proxy forwards to
localhost.
| Tool | How it shows a Pod |
|---|---|
kubectl get pod -o wide | READY n/m, STATUS (a display string, not the phase), RESTARTS, IP, NODE |
kubectl describe pod | Per-container state, last state, exit code, probes, events |
containerd (crictl pods, crictl ps) | The sandbox and each container as separate runtime objects |
| Docker Compose | No Pod concept: each service is its own network endpoint |
| Helm / Kustomize | Never create Pods: they template the controller that does |
Fix / how to use it: keep one main concern per Pod and add containers only when they must share the network or a volume and the lifecycle (a proxy, a log shipper, Nginx in front of php-fpm). Anything that scales independently (the queue worker, the scheduler) gets its own Deployment.
Init containers Important
In plain words: Init containers run before the app containers, one at a time, and each must finish successfully. They prepare things: wait for a dependency, render a config file, fix permissions on a volume.
Common misunderstanding: "An init container runs once per deploy." It runs once per Pod start, and again whenever the Pod is recreated. The docs: "Because init containers can be restarted, retried, or re-executed, init container code should be idempotent." Running php artisan migrate in an init container means every new replica (and every scale-up) races to migrate.
Definition: "Init containers always run to completion" and "Each init container must complete successfully before the next one starts." If one fails, the kubelet restarts it according to the Pod's restartPolicy (for Always and OnFailure); with Never the Pod fails. Regular init containers "do not support the lifecycle, livenessProbe, readinessProbe, or startupProbe fields". How init and sidecar requests add up to the Pod's effective request is covered in the scheduling chapter.
Pod with initContainers [wait-for-redis, render-config] and containers [app]
1 wait-for-redis loops until redis answers PING, exits 0
2 render-config writes /config/app.yaml into an emptyDir, exits 0 (Initialized = True)
3 app starts and reads /config/app.yaml
-> if render-config exits 1: restart with backoff (restartPolicy Always), app never starts, STATUS Init:CrashLoopBackOffReal scenarios: waiting for a database DNS name in a fresh namespace; downloading a model file into an emptyDir; chown of a volume mounted from a cloud disk; cloning data from the previous StatefulSet member (the replicated MySQL tutorial does this with an init container).
| Tool | Init container support |
|---|---|
| Kubernetes | spec.initContainers, sequential, STATUS shows Init:0/2, Init:Error, Init:CrashLoopBackOff |
| Docker Compose | No equivalent; depends_on with condition: service_completed_successfully ("a dependency is expected to run to successful completion") comes closest |
| Helm | Often generates "wait-for" init containers; hooks (pre-install Jobs) are the better place for migrations |
| Argo CD | PreSync hook Jobs ("Executes prior to the application of the manifests") for once-per-release work |
Fix: keep init containers idempotent and quick; move once-per-release work (migrations) into a Job (Laravel has migrate-job.yaml); prefer the app's own retry over "wait-for" loops where possible, because a dependency can also disappear after start.
Sidecar containers: restartable init containers Must-know
In plain words: A sidecar is a helper container that must run for the whole life of the Pod, start before the app and stop after it. Kubernetes models it as an init container that is allowed to keep running.
Common misunderstanding: "A sidecar is just a second container in containers." That still works, but then there is no ordering: the app may start before its proxy, the proxy may receive SIGTERM before the app has finished draining, and a Job with such a sidecar never completes. Only an entry in initContainers with restartPolicy: Always is a native sidecar.
Definition: "Kubernetes implements sidecar containers as a special case of init containers; sidecar containers remain running after Pod startup." After a sidecar is started ("the kubelet has set the started status for that init container to true", either when its process runs or when its startupProbe succeeds), the kubelet moves to the next init container. Sidecars support probes; "If a readinessProbe is specified for this init container, its result will be used to determine the ready state of the Pod." On termination "the kubelet postpones terminating sidecar containers until the main application container has fully stopped" and shuts them down "in the opposite order of their appearance in the Pod specification". In a Job, the sidecar "does not prevent the Job from completing after the main container has finished". Sidecars ignore the Pod-level restartPolicy; they always restart. Stages: alpha v1.28, on by default since v1.29, stable in v1.33.
initContainers: [nginx (restartPolicy: Always)] containers: [php-fpm]
start: nginx started -> php-fpm started -> Pod Ready when both probes pass
stop: php-fpm gets its stop signal (preStop first) -> php-fpm exits
-> only now nginx gets its stop signal -> nginx exits -> Pod gone
Job: main container exits 0 -> sidecar is terminated -> Job CompleteReal scenarios:
- A service-mesh proxy (Istio, Linkerd) that must be up before the app makes its first outbound call and must stay up while the app drains.
- A Cloud SQL or database proxy for a migration Job: with a regular second container the Job hangs forever after the migration finishes.
- A log forwarder that should flush the app's last lines after the app exits.
- Nginx in front of php-fpm, where Nginx must keep returning the responses php-fpm is finishing (PHP Pods).
| Tool | Sidecar behaviour |
|---|---|
| Kubernetes v1.33+ | Native sidecars stable; restartPolicy: Always on an init container |
| Istio, Linkerd | Can inject their proxy as a native sidecar on clusters that support it |
| Helm charts | Older charts put sidecars in containers; check before using them in Jobs |
| Docker Compose | No ordering at stop; depends_on orders start only |
Fix: put helpers that the app depends on (proxies, Nginx in front of FPM, log flushers) in initContainers with restartPolicy: Always, in the order they must start; give them a startupProbe if "process started" is not the same as "ready to serve"; expect non-zero exit codes from sidecars at Pod termination ("exit codes different from 0 ... for sidecar containers are normal on Pod termination").
Ephemeral containers and kubectl debug Important
In plain words: An ephemeral container is a temporary debugging container you add to a running Pod, for example a BusyBox shell next to a distroless Go binary that has no shell.
Common misunderstanding: "I can kubectl exec into any container." Only if the image has the binary you exec (a shell). Distroless images have none, and kubectl edit cannot add a container to a running Pod. Ephemeral containers are the supported way in.
Definition: Ephemeral containers (stable since v1.25) "lack guarantees for resources or execution, and they will never be automatically restarted"; they "may not have ports", so probes are disallowed; they are created "using a special ephemeralcontainers handler in the API rather than by adding them directly to pod.spec". kubectl debug -it <pod> --image=busybox:1.28 --target=<container> adds one; --target "targets the process namespace of another container", so ps shows the app's processes. kubectl debug <pod> --copy-to=<new> --share-processes creates a copy of the Pod instead (useful when the original is crash-looping), and kubectl debug node/<node> -it --image=ubuntu runs a Pod in the node's host namespaces.
kubectl debug -it orders-api-7d4b9c-x2kq --image=busybox:1.28 --target=api
1 kubectl PATCHes the Pod's ephemeralcontainers subresource
2 kubelet starts "debugger-xxxxx" in the Pod's network namespace and the target's process namespace
3 you get a shell: wget -qO- localhost:8080/readyz ; ps ; ls /proc/1/root
4 exit: the container stays listed as Terminated in the Pod status until the Pod is replacedReal scenarios: checking what /readyz returns from inside the Pod; reading /proc/1/environ of a distroless process; running tcpdump with --profile=netadmin; copying a crash-looping Pod with a changed command (--copy-to ... -- sh) to look around.
| Tool | Debugging route |
|---|---|
kubectl exec | Needs a binary in the image; fine for php-fpm (Debian base) |
kubectl debug (ephemeral) | Any image; profiles general, baseline, restricted, netadmin, sysadmin |
| Docker | docker exec, or docker run --pid container:<id> for a debug image |
distroless :debug tags | A BusyBox shell baked into a variant image (rebuild needed) |
Fix: keep production images shell-less and debug with kubectl debug --target; restrict who may create ephemeral containers through RBAC (pods/ephemeralcontainers), covered in Kubernetes Security.
Pod phases (Pending Running Succeeded Failed Unknown) and container states Must-know
In plain words: The phase is a one-word summary of where the whole Pod is in its life; each container separately is Waiting, Running or Terminated. kubectl get pods shows neither exactly: its STATUS column is a friendlier mix.
Common misunderstanding: "CrashLoopBackOff and Terminating are phases." They are display strings. The docs: "Make sure not to confuse Status, a kubectl display field for user intuition, with the pod's phase." A crash-looping Pod is usually in phase Running.
Definition: The five phases, quoted from the Pod lifecycle docs:
| Phase | Meaning (docs) |
|---|---|
Pending | "accepted by the Kubernetes cluster, but one or more of the containers has not been set up and made ready to run", including scheduling and image download time |
Running | "bound to a node, and all of the containers have been created. At least one container is still running, or is in the process of starting or restarting" |
Succeeded | "All containers in the Pod have terminated in success, and will not be restarted" |
Failed | "All containers in the Pod have terminated, and at least one container has terminated in failure" |
Unknown | "the state of the Pod could not be obtained", typically "an error in communicating with the node" |
Container states are Waiting (pulling, applying Secrets, or backing off; with a Reason such as ContainerCreating, ImagePullBackOff, CrashLoopBackOff), Running (any postStart hook "has already executed and finished") and Terminated (reason, exit code, start and finish time; preStop "runs before the container enters the Terminated state"). Pod conditions add detail: PodScheduled, PodReadyToStartContainers, Initialized, ContainersReady, Ready, DisruptionTarget. Since v1.27 the kubelet moves a deleted Pod to Failed or Succeeded before it disappears from the API.
STATUS column over time for a Pod whose image tag does not exist
Pending ContainerCreating -> ErrImagePull -> ImagePullBackOff -> ErrImagePull ... (phase: Pending)
STATUS for a Pod whose app exits 1 at start (restartPolicy Always)
Running -> Error -> CrashLoopBackOff -> Running -> Error -> CrashLoopBackOff ... (phase: Running)Real scenarios: a Pod Pending for minutes with event FailedScheduling (no node has the requested CPU; scheduling chapter); Pending with ImagePullBackOff (typo in the tag or missing pull secret); Unknown on every Pod of one node after a network partition; Job Pods ending in Succeeded and lingering until TTL or history limits remove them.
| Tool | Where to read phase and state |
|---|---|
kubectl get pod -o jsonpath='{.status.phase}' | The real phase |
kubectl describe pod | State, Last State, Reason, Exit Code, conditions, events |
kubectl get events --field-selector involvedObject.name=<pod> | Scheduling, pulling, probe and kill events |
| Argo CD / Lens / k9s | Summarise health from conditions, not only phase |
Fix: script against .status.phase and conditions (kubectl wait --for=condition=Ready), never against the STATUS column; read Last State and Exit Code in describe for the previous crash.
restartPolicy and CrashLoopBackOff Must-know
In plain words: restartPolicy says whether the kubelet restarts a container that stopped. If a container keeps crashing, the kubelet waits longer and longer between attempts; that waiting is what CrashLoopBackOff means.
Common misunderstanding: "A process that exits 0 on purpose is not restarted." Under restartPolicy: Always (the only value a Deployment allows) exit 0 is restarted like any crash, and repeated exits get the same exponential backoff. A Laravel worker with --max-jobs=10 that exits every few seconds will soon sit in CrashLoopBackOff although nothing is wrong.
Definition: "The spec of a Pod has a restartPolicy field with possible values Always, OnFailure, and Never. The default value is Always." It applies to app containers and regular init containers; sidecars always restart. Restarts happen in place (same Pod, same node). The kubelet "restarts them with an exponential backoff delay (10s, 20s, 40s, …), that is capped at 300 seconds (5 minutes). Once a container has executed for 10 minutes without any problems, the kubelet resets the restart backoff timer for that container." Deployments, StatefulSets and DaemonSets require Always; Jobs use OnFailure or Never. Newer, gate-controlled options: per-container restartPolicy and restartPolicyRules (restart only on given exit codes, ContainerRestartRules), a node-level maximum delay (KubeletCrashLoopBackOffMax, beta since v1.35) and a reduced default decay (ReduceDefaultCrashLoopBackOffDecay, alpha since v1.33).
Container exits at 00:00 (restartPolicy Always)
00:00 exit 1 -> immediate restart (first crash)
00:01 exit 1 -> wait 10 s STATUS CrashLoopBackOff
00:12 exit 1 -> wait 20 s
00:33 exit 1 -> wait 40 s ... 80 s, 160 s, then 300 s between attempts
-> a fix rolled out as a new ReplicaSet starts fresh Pods with no backoff historyReal scenarios: a missing environment variable makes the app exit 1 at start (kubectl logs --previous shows why); a liveness probe kills a slow-starting JVM every 30 s; a queue:work --max-time=3600 worker restarts once an hour with no backoff because it ran longer than 10 minutes; an OOM-killed container shows Last State: Terminated, Reason: OOMKilled, Exit Code: 137.
| Policy / tool | Exit 0 | Exit non-zero | Fits |
|---|---|---|---|
Always | Restart | Restart | Deployments, StatefulSets, DaemonSets |
OnFailure | Done | Restart in place (counts toward Job backoffLimit) | Jobs whose Pods should retry on the same node |
Never | Done | Pod Failed; the Job controller creates a new Pod | Jobs with podFailurePolicy |
Docker --restart | always / on-failure / no | Similar, per container | Single hosts |
Supervisor (autorestart) | Configurable | Configurable | Laravel workers on VMs |
Fix: let processes that exit on purpose run long enough (--max-time of an hour, not --max-jobs=10); read kubectl logs <pod> --previous and Last State; fix the cause rather than raising probe thresholds; remember that a new rollout is the fastest way out of a long backoff.
Probes: liveness probe, readiness probe, startup probe Must-know
In plain words: The kubelet asks each container three different questions on a timer. Startup: "are you done booting?" Liveness: "are you stuck so badly that only a restart helps?" Readiness: "may I send you requests right now?"
Common misunderstanding: "Readiness and liveness are the same check with different names." They have opposite consequences. A failed readiness probe only takes the Pod out of Service endpoints and keeps probing; a failed liveness probe kills the container. Pointing both at an endpoint that checks the database turns a database blip into a fleet-wide restart.
Definition: From the probe concept page: startup probe: "If a startup probe is configured, Kubernetes does not execute liveness or readiness probes until the startup probe succeeds"; it runs only at startup, and on failure "the kubelet kills the container, and the container is subjected to its restart policy". Liveness probe: "Liveness probes determine when to restart a container", for example "a deadlock, where an application is running, but unable to make progress"; "Liveness probes do not wait for readiness probes to succeed". Readiness probe: "Readiness probes determine when a container is ready to accept traffic"; on failure "the EndpointSlice controller removes the Pod's IP address from the EndpointSlices of all Services that match the Pod", and "Readiness probes run on the container during its whole lifecycle". If a probe is not defined "the kubelet always considers the result as Success", but "For readiness probes specifically, the result is considered Failure before the initial delay."
orders-api Pod start (startup period 2 s x 30, liveness 10 s x 3, readiness 5 s x 2)
t=0 container starts; startupProbe GET /startupz -> 503 (warming up)
t=6 /startupz -> 200: startup done; liveness and readiness begin
t=6 readinessProbe GET /readyz -> 200 -> Ready=True -> endpoint ready, traffic arrives
t=300 database unreachable: /readyz 503 twice -> Ready=False, endpoint removed; /livez still 200, no restart
t=420 database back: /readyz 200 -> Ready=True again
t=900 goroutine deadlock: /livez times out 3 x 10 s -> kubelet kills the container -> restartReal scenarios:
- A Laravel Pod that runs
php artisan optimizein its entrypoint needs 15 s before FPM listens: a startup probe allows that without a longinitialDelaySecondson liveness. - A Go service warms a cache from Redis for 40 s; readiness keeps it out of the Service until done.
- A liveness probe with
timeoutSeconds: 1against an endpoint that sometimes takes 1.5 s under load kills healthy containers exactly when traffic peaks ("restarting of container under high load", in the docs' caution). - An app that can crash on its own when unhealthy may not need liveness at all: "the kubelet will automatically perform the correct action in accordance with the Pod's
restartPolicy."
| Product | Health-check model |
|---|---|
| Kubernetes | Startup, liveness, readiness per container, run by the kubelet |
| Docker / Compose | One HEALTHCHECK; Kubernetes ignores it |
| AWS ALB / NLB target groups | Their own HTTP/TCP checks against the Pod IP (with IP targets), separate from readiness unless readiness gates link them |
| Nginx Ingress, Gateway API implementations | Route to ready endpoints from EndpointSlices |
| Laravel | /up route: 200 when the app boots, 500 otherwise; DiagnosingHealth event for extra checks |
Fix: three endpoints with three meanings: /livez local and cheap (no dependencies), /startupz until warm-up ends, /readyz including the dependencies the Pod cannot serve without; a startup probe instead of a large initialDelaySeconds; liveness thresholds looser than readiness (the docs' "common pattern": same endpoint, higher failureThreshold). The Go service implements exactly this.
Probe mechanisms: exec probe, httpGet probe, tcpSocket probe, grpc probe Important
In plain words: A probe either runs a command inside the container (exec), sends an HTTP GET (httpGet), opens a TCP connection (tcpSocket) or calls the gRPC health service (grpc). Each probe uses exactly one.
Common misunderstanding: "An exec probe with curl is the most flexible, so use it everywhere." It needs curl (or a shell) in the image, which distroless images do not have, and it forks processes on every run: the docs warn that exec probes "might introduce an overhead on the cpu usage of the node" at high Pod density. httpGet is executed by the kubelet itself and needs nothing in the image.
Definition: "Each probe must define exactly one of these four mechanisms":
| Mechanism | Success when | Run by | Notes from the docs |
|---|---|---|---|
exec | Command exits 0 | Inside the container | Forks processes on every probe |
httpGet | Status >= 200 and < 400 | kubelet, to the Pod IP | Default headers User-Agent: kube-probe/<version> and Accept: */*; HTTPS skips certificate verification; body read stops after 10 KiB; only same-host redirects are followed |
tcpSocket | Port accepts the connection | kubelet "at the node, not in the Pod" | A connection closed right after opening still counts as healthy; no Service names in host |
grpc | Health response status is SERVING | kubelet | Stable since v1.27; port must be a number (no named ports); optional service field to distinguish probe types; TLS mode is a newer gated option |
httpGet probe on /readyz, timeoutSeconds 1
1 kubelet opens TCP to 10.1.7.23:8080 (Pod IP, not localhost)
2 sends GET /readyz with Host 10.1.7.23:8080, User-Agent kube-probe/1.37
3 reads status line: 503 -> Failure (any 2xx/3xx would be Success)
4 stops reading the body after 10 KiB; no answer within 1 s -> FailureReal scenarios: php-fpm speaks FastCGI, not HTTP, so its own container gets a tcpSocket probe on 9000 and the HTTP check goes to Nginx's /up; Redis gets an exec probe with redis-cli ping (the image has the binary); a Go gRPC service registers grpc_health_v1 and uses grpc: {port: 9090}; an httpGet probe pointed at a 2 MB status page produces "connection reset by peer" noise in the app's logs.
| Probe mechanism | Go service | Laravel (php-fpm + Nginx) | Redis |
|---|---|---|---|
httpGet | /livez, /startupz, /readyz | Nginx /up | n/a |
tcpSocket | Possible, weaker | php-fpm :9000 | :6379 liveness |
exec | Only via a subcommand of the binary (no shell) | php -r ... possible but heavy | redis-cli ping readiness |
grpc | google.golang.org/grpc/health server | n/a | n/a |
The gRPC form, from the Kubernetes example (an etcd Pod):
livenessProbe:
grpc:
port: 2379 # numeric; named ports are not allowed for grpc
initialDelaySeconds: 10Fix: prefer httpGet for HTTP apps, grpc for gRPC apps, tcpSocket for protocols the kubelet cannot speak (FastCGI, Redis) and exec only when the image has the tool and the check needs it; keep probe responses tiny.
Probe knobs: initialDelaySeconds, periodSeconds, timeoutSeconds, failureThreshold, successThreshold Must-know
In plain words: Five numbers decide how soon a probe starts, how often it runs, how long it may take, and how many failures or successes in a row flip the result.
Common misunderstanding: "initialDelaySeconds: 60 is the safe way to handle a slow start." It delays liveness for every start, including the fast ones, and still kills a start that takes 61 s. The docs' rule: if the container usually starts in more than initialDelaySeconds + failureThreshold × periodSeconds, add a startup probe on the same endpoint with a large enough failureThreshold.
Definition: The probe reference, field by field:
| Field | Default | Minimum | Meaning |
|---|---|---|---|
initialDelaySeconds | 0 | 0 | Seconds after container start before the probe begins; with a startup probe, liveness and readiness delays start after it succeeds |
periodSeconds | 10 | 1 | How often; while not Ready, readiness may run more often "to make the Pod ready faster" |
timeoutSeconds | 1 | 1 | Seconds before one attempt counts as a failure |
failureThreshold | 3 | 1 | Consecutive failures that flip the result |
successThreshold | 1 | 1 | Consecutive successes after a failure; must be 1 for liveness and startup |
terminationGracePeriodSeconds (probe level) | Pod value | 1 | Grace period when liveness/startup kills the container; not allowed on readiness |
Worst-case time to act = initialDelaySeconds + failureThreshold x periodSeconds (+ timeoutSeconds)
startup 0 + 30 x 2 = 60 s to boot before the first restart
liveness 0 + 3 x 10 = 30 s of a wedged process before a kill
readiness 0 + 2 x 5 = 10 s of failures before the endpoint is removedReal scenarios: a probe timeoutSeconds: 1 that fails only when GC pauses exceed a second; failureThreshold: 1 on liveness turning a single slow response into a restart; readiness successThreshold: 3 to avoid flapping a Pod back into rotation; a startup budget computed for the laptop (5 s) that is far too low on a busy node.
| Failure mode | Symptom | Knob that fixes it |
|---|---|---|
| Slow boot killed by liveness | CrashLoopBackOff, event "Liveness probe failed" during start | Startup probe with enough failureThreshold × periodSeconds |
| Restarts under load | Restarts correlate with traffic peaks | Higher timeoutSeconds / failureThreshold, cheaper endpoint |
| Flapping in and out of the Service | Endpoint churn, 5xx spikes | Higher readiness successThreshold or failureThreshold |
| Traffic before ready | Errors right after rollout | Add a readiness probe; minReadySeconds on the Deployment |
| Probe process pile-up | Many exec processes, CPU on the node | Switch to httpGet / tcpSocket; raise periodSeconds |
Fix: compute the three worst-case times explicitly in a comment next to the probes (the Go manifest does), and size them for a busy node, not an idle one.
Graceful termination: preStop hook, terminationGracePeriodSeconds, SIGTERM, SIGKILL, endpoint removal Must-know
In plain words: When a Pod is deleted, Kubernetes at the same time tells the load-balancing layer to stop sending it traffic and tells the containers to stop. The app gets a polite signal first and, after a deadline, a forced kill. Doing this without dropping requests means: keep serving for a few seconds, then finish what is in flight, then exit before the deadline.
Common misunderstanding: "On SIGTERM, close the listener and you are done." The endpoint removal is asynchronous and reaches kube-proxy, the Ingress controller and the cloud load balancer seconds later; until then new connections still arrive. And "the grace period starts after preStop" is also wrong: "The Pod's termination grace period countdown begins before the PreStop hook is executed".
Definition: The termination flow in the docs: the Pod is marked with a deletion time and a grace period (default 30 s); the kubelet runs any preStop hook ("If the preStop hook is still running after the grace period expires, the kubelet requests a small, one-off grace period extension of 2 seconds"); then "The kubelet triggers the container runtime to send a TERM signal to process 1 inside each container", in "an arbitrary order" unless sidecars are involved; "Many container runtimes respect the STOPSIGNAL value defined in the container image". In parallel, terminating endpoints "always have their ready status as false", with serving reporting actual readiness for draining-aware load balancers. "When the grace period expires, if there is still any container running in the Pod, the kubelet triggers forcible shutdown. The container runtime sends SIGKILL". Hooks: preStop "must complete before the TERM signal to stop the container can be sent"; handlers are exec (in the container), httpGet, and sleep (run by the kubelet; stable in v1.34); hook delivery is "at least once". A custom per-container stop signal (lifecycle.stopSignal) is alpha behind ContainerStopSignals (since v1.33).
kubectl rollout restart deployment/orders-api (one old Pod, grace 30 s)
t=0.0 Pod marked for deletion; EndpointSlice: ready=false, terminating=true
t=0.0 kubelet: preStop sleep 5 s starts; the app still serves normally
t=0-3 kube-proxy, Ingress, ALB drop the endpoint (each at its own pace)
t=5.0 SIGTERM to PID 1 -> /readyz 503, http.Server.Shutdown: listener closed, in-flight requests finish
t=7.4 last request done -> process exits 0 -> container Terminated
t=30 (only if still running) SIGKILL; exit code 137Real scenarios:
- A Go service exits on SIGTERM in 50 ms and clients see a burst of 502s on every rollout: no delay before closing the listener.
- A PHP container started through a shell script (
CMD sh start.shwithoutexec): the shell is PID 1, the signal never reaches FPM, and every stop takes the full 30 s and ends in SIGKILL. - A queue job that takes 5 minutes is killed mid-way on every deploy because the grace period is the default 30 s.
- php-fpm's image sets
STOPSIGNAL SIGQUIT("graceful stop" in the FPM man page; SIGTERM would be "immediate termination"); the runtime sends SIGQUIT, not SIGTERM.
| Runtime / tool | Stop signal and deadline |
|---|---|
| Kubernetes | preStop, then TERM (or image STOPSIGNAL), SIGKILL at terminationGracePeriodSeconds |
| containerd, CRI-O | Default stop signal SIGTERM; honour the image's STOPSIGNAL |
| Docker | docker stop: SIGTERM (or STOPSIGNAL), SIGKILL after 10 s by default |
| Nginx | TERM/INT = "fast shutdown", QUIT = "graceful shutdown"; the official image sets STOPSIGNAL SIGQUIT |
| php-fpm | SIGINT/SIGTERM "immediate termination", SIGQUIT "graceful stop"; process_control_timeout (default 0) bounds how long children get to react to the master's signal |
Go net/http | Server.Shutdown "first closing all open listeners, then closing all idle connections, and then waiting indefinitely for connections to return to idle" unless the context expires |
Laravel queue:work | On SIGQUIT, SIGTERM or SIGINT "the worker will finish its current job before exiting" |
Fix: a preStop delay (the sleep action needs no shell) long enough for the traffic layer, then a bounded drain in the app, with preStop + drain < terminationGracePeriodSeconds; exec-form entrypoints so the app is PID 1; a grace period above the longest request or job; the right stop signal for the process (SIGQUIT for FPM and Nginx, which their images already set).
Readiness gates and Pod conditions Good to know
In plain words: A readiness gate is an extra condition, set by some other controller, that must also be true before the Pod counts as Ready. The classic use: "the cloud load balancer has registered this Pod and its health check passes".
Common misunderstanding: "Container readiness is the whole story." With a cloud load balancer that targets Pod IPs directly, Kubernetes can mark a new Pod Ready (and the Deployment can delete an old one) before the load balancer has finished registering the new target, so a fast rollout can leave the load balancer with no healthy targets.
Definition: "set readinessGates in the Pod's spec to specify a list of additional conditions that the kubelet evaluates for Pod readiness"; the Pod is ready "only when both the following statements apply: All containers in the Pod are ready. All conditions specified in readinessGates are True." A missing condition defaults to False; when containers are ready but a gate is not, the Pod has ContainersReady but not Ready. Conditions are set through the status API (kubectl patch does not support status), typically by a controller. Stable since v1.14.
AWS Load Balancer Controller with Pod readiness gate injection
1 new Pod: containers ready -> ContainersReady=True, gate target-health.../orders-api = False -> Ready=False
2 controller registers 10.1.7.31 in the target group, ALB health check passes
3 controller sets the gate condition True -> Ready=True -> Deployment counts the Pod as available
4 only now does the rollout scale the old ReplicaSet downReal scenarios: AWS Load Balancer Controller and GKE container-native load balancing (NEGs) both use readiness gates to slow rollouts to the speed of the cloud load balancer; custom operators gate readiness on "replica has caught up".
| Condition | Set by | Meaning |
|---|---|---|
PodScheduled | scheduler | Bound to a node |
PodReadyToStartContainers | kubelet | Sandbox, network and volumes ready (stable v1.37) |
Initialized | kubelet | Init containers done |
ContainersReady | kubelet | Every container ready |
Ready | kubelet | Containers ready and all gates true: add to Services |
DisruptionTarget | control plane | About to be terminated by a disruption (eviction, preemption) |
Fix: if your load balancer targets Pod IPs, enable its readiness gate support; otherwise leave readinessGates empty.
Resource requests and limits (preview) Good to know
In plain words: Requests are what the scheduler reserves for a container; limits are the ceiling the node enforces. They are covered in depth in Resources, Scheduling & Autoscaling; this block lists only what workloads need.
Common misunderstanding: "Limits are optional decoration." A container over its memory limit is OOM-killed (Reason: OOMKilled, exit code 137) and restarted under restartPolicy, which looks like a crash loop; a Pod without requests is the first to be evicted under node pressure; an HPA on CPU utilisation needs CPU requests to compute a percentage.
Definition: Per container: resources.requests.cpu|memory and resources.limits.cpu|memory. Their combination decides the QoS class (Guaranteed, Burstable, BestEffort), fixed at Pod creation. Sidecar requests are added to the app containers' requests, and their order in initContainers changes the Pod's effective request.
orders-api: requests cpu 100m memory 64Mi, limits memory 128Mi
1 scheduler places the Pod only on a node with 100m CPU and 64Mi free (allocatable minus requests)
2 under load the container may use more CPU (no CPU limit) if the node has it
3 memory grows past 128Mi -> kernel OOM kill in the container's cgroup -> restart (RESTARTS +1)Real scenarios: a Laravel worker leaking memory per job is OOM-killed every hour; --memory= on queue:work makes it exit cleanly before the limit instead.
| Setting | Workload consequence |
|---|---|
| No requests and no limits | Placed anywhere, BestEffort, evicted first |
| Limits but no requests | Kubernetes "copies the limit you specified and uses it as the requested value": the limit is reserved |
| Requests = limits (all) | Guaranteed QoS |
| Memory limit too low | OOMKilled, restarts |
| CPU limit too low | Throttling: slow probes, liveness timeouts |
Fix: always set requests; set a memory limit; be careful with CPU limits on latency-sensitive services; size from measurements, as the scheduling chapter shows.
Labels, selectors, matchLabels and the immutable selector Must-know
In plain words: Labels are key/value tags on objects; selectors are queries over labels. A Deployment finds "its" Pods, a Service finds its endpoints and a PDB finds what it protects only through selectors.
Common misunderstanding: "I can rename the app label on a running Deployment." The selector of a Deployment (also StatefulSet, DaemonSet, ReplicaSet, Job) is immutable in apps/v1: "A Deployment's label selector is immutable after creation"; "If you must change the selector, you have to delete the Deployment and recreate it." And overlapping selectors between two controllers are not prevented: "Kubernetes doesn't stop you from overlapping, and if multiple controllers have overlapping selectors those controllers might conflict and behave unexpectedly."
Definition: Label keys and values: name segments "must be 63 characters or less", an optional DNS prefix (app.kubernetes.io/name). Two selector kinds: equality-based (=, ==, !=) and set-based (in, notin, exists); in objects, selector.matchLabels (a map, ANDed) and selector.matchExpressions. In apps/v1, .spec.selector must be set explicitly and must match .spec.template.metadata.labels. The recommended labels are app.kubernetes.io/name, instance, version, component, part-of, managed-by. Controllers add their own: pod-template-hash (Deployment), statefulset.kubernetes.io/pod-name and apps.kubernetes.io/pod-index (StatefulSet), batch.kubernetes.io/job-completion-index (Indexed Job).
selector matchLabels {app.kubernetes.io/name: orders-api}
Deployment orders-api ─▶ ReplicaSet orders-api-7d4b9c (adds pod-template-hash=7d4b9c to selector and Pods)
Service orders-api ─▶ every Ready Pod with app.kubernetes.io/name=orders-api (both ReplicaSets during a rollout)
PDB orders-api ─▶ same Pods, counts healthy ones
HPA ─▶ scaleTargetRef by name (not by selector)Real scenarios: a second Deployment orders-api-canary with the same selector fights the first one over Pods; a Service with a typo in its selector has zero endpoints and every request gets "connection refused"; Helm upgrades fail with field is immutable after a chart changed selector labels; putting version into matchLabels makes every release need a new Deployment.
| Object | Selector type | Mutable? |
|---|---|---|
| Deployment, ReplicaSet, StatefulSet, DaemonSet | matchLabels / matchExpressions | No (immutable) |
| Job | Generated by default (controller-uid) | No |
| Service | Plain map (equality only) | Yes |
| PodDisruptionBudget | matchLabels / matchExpressions | Yes |
| NetworkPolicy, topology spread, affinity | Label selectors | Yes |
Fix: choose a stable selector once (app.kubernetes.io/name, plus instance when one chart is installed several times), put changing labels (version) only in the template, never in the selector; give canaries a distinct label that only the canary Service selects.
imagePullPolicy and image tags vs digests Important
In plain words: imagePullPolicy decides whether the kubelet asks the registry before starting a container. A tag is a name that can move; a digest names exact bytes.
Common misunderstanding: "imagePullPolicy: Always downloads the whole image on every start." The runtime "resolves the image tag or name to a digest, and downloads any layers that are not already cached locally"; the docs call Always efficient "as long as the registry is reliably accessible". The real costs are the registry dependency at start time and mixed versions when a tag moves.
Definition: IfNotPresent pulls only if the image is missing; Always resolves on every container start; Never never pulls. Defaults when the field is omitted: digest given → IfNotPresent; tag :latest or no tag → Always; any other tag → IfNotPresent; the value "is always set when the object is first created, and is not updated if the image's tag or digest later changes". With a tag, "you might end up with a mix of Pods running the old and new code"; a digest "pins the code that you run". With name:tag@sha256:... "Only the digest will be used for pulling."
Tag 1.4 re-pushed while orders-api runs 3 Pods with imagePullPolicy IfNotPresent
1 node-1 and node-2 have the old 1.4 cached: existing and restarted Pods keep the old code
2 a Pod rescheduled to node-3 (no cache) pulls the NEW 1.4
3 three Pods, one tag, two versions; rollback "to 1.4" is now ambiguous
-> with image: ghcr.io/acme/orders-api@sha256:... every node runs the same bytesReal scenarios: a hotfix re-pushed under the same tag never reaches Pods on nodes that cached the old one; :latest in a manifest silently becomes Always and Pods fail to start during a registry outage; GitOps tooling writes the digest back into the manifest after CI.
| Reference form | Default pull policy | Reproducible? |
|---|---|---|
orders-api | Always (means :latest) | No |
orders-api:latest | Always | No |
orders-api:1.4.2 | IfNotPresent | Only if the tag is immutable in the registry |
orders-api@sha256:... | IfNotPresent | Yes |
orders-api:1.4.2@sha256:... | IfNotPresent (digest wins) | Yes, and readable |
Fix: deploy name:tag@sha256:<digest> written by CI (Kustomize images:, Helm values, Argo CD Image Updater), make release tags immutable in the registry, and leave imagePullPolicy at its default; tagging and registries are in Images & Dockerfiles.
ReplicaSet Important
In plain words: A ReplicaSet keeps N copies of one Pod template running. It does not know about versions; a Deployment creates one ReplicaSet per version and moves Pods between them.
Common misunderstanding: "I should create ReplicaSets for simple cases." The docs: "we recommend using Deployments instead of directly using ReplicaSets", and "you may never need to manipulate ReplicaSet objects". A ReplicaSet does not update existing Pods when its template changes; only new Pods get the new template.
Definition: spec.replicas, spec.selector, spec.template. The controller counts Pods matching the selector (also bare Pods that happen to match: it adopts them) and creates or deletes Pods to reach replicas. Each ReplicaSet created by a Deployment gets the pod-template-hash label (also added to its selector and its Pods), "the same as the pod-template-hash label on the ReplicaSet", so two versions never select each other's Pods.
kubectl scale deployment/orders-api --replicas=5
1 Deployment controller sets replicas 5 on the CURRENT ReplicaSet (no new revision)
2 ReplicaSet controller sees 3 matching Pods, creates 2
3 kubectl get rs: orders-api-7d4b9c DESIRED 5 CURRENT 5 READY 3 -> 5 as probes passReal scenarios: kubectl get rs showing ten old ReplicaSets at 0/0 (revision history); a hand-made Pod with the app's labels silently counted as one of the replicas; deleting a Pod and watching the ReplicaSet create a replacement within a second.
| Object | Owns | Creates revisions? |
|---|---|---|
| ReplicaSet | Pods | No |
| Deployment | ReplicaSets | Yes, one per template change |
| ReplicationController (legacy) | Pods | No; equality selectors only |
Fix: manage ReplicaSets only through their Deployment; read them to understand a rollout (kubectl get rs -l app.kubernetes.io/name=orders-api).
Deployment and rolling update: RollingUpdate, Recreate, maxSurge, maxUnavailable, minReadySeconds, progressDeadlineSeconds Must-know
In plain words: A Deployment says "run this Pod template N times". When you change the template, it starts new Pods and stops old ones in steps, never going below a minimum of available Pods or above a maximum of counted Pods (Pods still terminating are not counted, so the real total can be higher for a while).
Common misunderstanding: "maxUnavailable: 0 means zero downtime." It means the controller never scales the old ReplicaSet below replicas available Pods. Downtime still happens if new Pods are "available" before they can really serve (no readiness probe, minReadySeconds: 0 with a flaky start) or if old Pods drop requests while terminating. The strategy controls counts; probes and termination control correctness.
Definition: .spec.strategy.type is RollingUpdate (default) or Recreate. With Recreate, "All existing Pods are killed before new ones are created" (the docs add this only holds "for upgrades"; a manually deleted Pod is replaced at once). With RollingUpdate: maxUnavailable (default 25%, "rounding down", cannot be 0 if maxSurge is 0) and maxSurge (default 25%, "rounding up", cannot be 0 if maxUnavailable is 0). With the defaults the Deployment keeps "at least 75%" and "at most 125%" of the desired Pods; for 4 replicas, "the number of Pods would be between 3 and 5". minReadySeconds: how long a new Pod must be ready "without any of its containers crashing, for it to be considered available" (default 0). progressDeadlineSeconds (default 600, must be greater than minReadySeconds): after it, the condition Progressing becomes False with reason: ProgressDeadlineExceeded, and "The Deployment controller will keep retrying". A rollout starts "if and only if the Deployment's Pod template (that is, .spec.template) is changed".
replicas 10, maxSurge 3, maxUnavailable 2, new image
1 bounds: counted Pods <= 13 (terminating ones excluded), available >= 8
2 new RS scaled to 3 (total 13); old RS scaled to 8 (available 8)
3 as each new Pod becomes available (Ready + minReadySeconds), old RS shrinks and new RS grows
4 new RS 10 / old RS 0 -> condition Progressing reason NewReplicaSetAvailable -> rollout complete
-> a second template change mid-rollout ("rollover") starts a third RS and scales the in-progress one down tooReal scenarios:
- Three replicas, defaults:
maxUnavailable25% rounds down to 0,maxSurgerounds up to 1, so one extra Pod at a time. - A cluster with no spare capacity:
maxSurge: 1leaves the surge PodPending;maxSurge: 0, maxUnavailable: 1replaces in place. - A service that cannot run two versions at once (incompatible cache format, a single-writer scheduler):
Recreate, with the downtime that implies. - A bad image: new Pods never become ready, the old ReplicaSet stays at its floor, and after
progressDeadlineSecondskubectl rollout statusexits 1.
| Strategy | Old and new at once? | Capacity during rollout | Fits |
|---|---|---|---|
RollingUpdate 25%/25% (default) | Yes | 75–125% of counted Pods, plus terminating ones | Most stateless services |
RollingUpdate maxSurge 1, maxUnavailable 0 | Yes | 100–100%+1 | Small replica counts, strict capacity |
RollingUpdate maxSurge 0, maxUnavailable 1 | Yes | N-1 to N | No spare cluster capacity |
Recreate | No | 0 during the switch | Single-writer processes, incompatible versions |
| Blue-green / canary (Argo Rollouts, Flagger, service mesh) | Controlled | Per strategy | See Deployment Strategies |
Fix: set readiness probes and a small minReadySeconds so "available" means "served traffic without crashing"; choose maxSurge/maxUnavailable from capacity and replica count; set progressDeadlineSeconds to a value CI can wait for and gate the pipeline on kubectl rollout status.
Revision history, rollout status, rollout undo, pause and resume Must-know
In plain words: Every template change is a numbered revision kept as an old ReplicaSet. kubectl rollout watches a rollout, lists revisions, goes back to one, and can pause a Deployment so several edits become one rollout.
Common misunderstanding: "rollout undo restores the previous manifest." It copies the previous revision's Pod template back (a new revision number) and nothing else: replicas, strategy, the Service, the ConfigMap the Pods read are not reverted. And with revisionHistoryLimit: 0 there is nothing to undo: "a new Deployment rollout cannot be undone, since its revision history is cleaned up."
Definition: "A Deployment's revision history is stored in the ReplicaSets it controls"; .spec.revisionHistoryLimit keeps 10 old ReplicaSets by default, cleaned up only after the Deployment is complete. CHANGE-CAUSE in the history comes from the annotation kubernetes.io/change-cause. .spec.paused: "any changes into the PodTemplateSpec of the paused Deployment will not trigger new rollouts as long as it is paused." Commands: kubectl rollout status (exit 0 when complete; non-zero "if the Deployment has exceeded the progression deadline"), rollout history [--revision=N], rollout undo [--to-revision=N], rollout pause, rollout resume, rollout restart (replaces all Pods without a manifest change). rollout works for Deployments, DaemonSets and StatefulSets, but "Currently only deployments support being paused."
Pause, batch two edits, resume, then roll back
1 kubectl rollout pause deployment/orders-api
2 kubectl set image deployment/orders-api api=ghcr.io/acme/orders-api:1.5.0
3 kubectl set env deployment/orders-api SHUTDOWN_TIMEOUT=15s (no rollout yet)
4 kubectl rollout resume deployment/orders-api -> ONE new ReplicaSet, revision 4
5 errors rise: kubectl rollout undo deployment/orders-api -> revision 3's template becomes revision 5Real scenarios: CI runs kubectl rollout status --timeout=10m and fails the job when the deadline passes; an on-call engineer runs rollout undo while the fix is prepared; a GitOps tool (Argo CD, Flux) reverts the undo on its next sync because Git still says 1.5.0, so in GitOps the rollback is a Git revert.
| Command | Deployment | StatefulSet | DaemonSet |
|---|---|---|---|
rollout status | Yes | Yes | Yes |
rollout history / undo | Yes (ReplicaSets) | Yes (ControllerRevisions) | Yes (ControllerRevisions) |
rollout pause / resume | Yes | No | No |
rollout restart | Yes | Yes | Yes |
Fix: keep revisionHistoryLimit small but non-zero (3–10); record the cause in the annotation or, better, in Git; in GitOps roll back in Git and let the controller follow.
StatefulSet: stable network identity, ordinal index, volumeClaimTemplates, headless Service, podManagementPolicy, partition Must-know
In plain words: A StatefulSet is for Pods that are not interchangeable. Each one has a number (0, 1, 2 ...), keeps its name and DNS record across restarts, and has its own disk that follows it to whatever node it lands on.
Common misunderstanding: "A StatefulSet makes a database highly available." It gives each member a stable identity and volume; replication, leader election, failover and backups are the database's (or an operator's) job. Three Postgres Pods in a StatefulSet without replication configuration are three unrelated, empty databases.
Definition: "StatefulSet Pods have a unique identity that consists of an ordinal, a stable network identity, and stable storage." Ordinals run "from 0 up through N-1" (or from .spec.ordinals.start); the hostname is $(statefulset name)-$(ordinal); a headless Service (clusterIP: None, named in serviceName, which you must create) gives each Pod the DNS name web-0.nginx.default.svc.cluster.local. volumeClaimTemplates create one PersistentVolumeClaim per Pod (www-web-0), and the volumes "are not deleted when the Pods, or StatefulSet are deleted" unless persistentVolumeClaimRetentionPolicy (whenDeleted, whenScaled: Retain or Delete; GA in v1.32) says so. Ordering (podManagementPolicy: OrderedReady, the default): Pods "are created sequentially, in order from {0..N-1}" and deleted "in reverse order"; each step waits for its predecessor "Running and Ready". Parallel launches and terminates all at once but keeps identities. Updates: RollingUpdate (default; "from the largest ordinal to the smallest", one at a time), OnDelete (only when you delete Pods), and an alpha Recreate (v1.37, behind StatefulSetRecreateStrategy). A partition N updates only ordinals >= N. maxUnavailable for StatefulSet rolling updates is beta and on by default in v1.37 (default 1). The StatefulSet "should not specify a pod.Spec.TerminationGracePeriodSeconds of 0".
Canary a new Redis image on a 3-member StatefulSet with a partition
1 kubectl patch sts cache -p '{"spec":{"updateStrategy":{"rollingUpdate":{"partition":2}}}}'
2 set the new image -> only cache-2 is deleted and recreated (same name, same PVC)
3 watch cache-2 for an hour; then partition 1 -> cache-1; then partition 0 -> cache-0
4 if cache-2 never becomes Ready: revert the template AND delete cache-2 (forced rollback)Real scenarios:
- Kafka, ZooKeeper, etcd and Elasticsearch members address each other as
name-N.service; a replacement must keep the name. - A rollout to a broken template under
OrderedReadystops at the highest ordinal and, per the docs, "it's not enough to revert the Pod template": the broken Pod must be deleted by hand. kubectl scale sts shop-redis --replicas=0before maintenance, because deleting a StatefulSet gives no ordering guarantee ("scale the StatefulSet down to 0 prior to deletion").- A node stops responding:
shop-redis-0is not simply started elsewhere, because a StatefulSet promises that "there is at most one Pod with a given identity running in a cluster"; force-deleting it is a deliberate operation ("In normal operation of a StatefulSet, there is never a need to force delete a StatefulSet Pod").
Does the database belong in a StatefulSet? A single Redis for queues and cache in a development or small production cluster: yes, as in the Laravel manifests. A production PostgreSQL or MySQL that the business depends on: run it either as a managed service (RDS, Cloud SQL, Azure Database) or through an operator (CloudNativePG, Percona, Zalando, Strimzi for Kafka) that adds replication, failover, backups and upgrades; some build on StatefulSets, while CloudNativePG "implements its own custom controller to manage PostgreSQL instances, instead of relying on the StatefulSet controller"; hand-written StatefulSets for primaries with replicas recreate badly what those projects already solved. The replication and failover theory is in Replication & Failover.
| Need | StatefulSet gives | You still need |
|---|---|---|
| Stable member names | name-N + headless Service DNS | Clients that use them |
| Per-member disk | volumeClaimTemplates, PVC per ordinal | A StorageClass, backups |
| Ordered start and stop | OrderedReady | Readiness that means "joined the cluster" |
| Staged upgrades | partition, OnDelete | Version compatibility between members |
| Failover, replication | Nothing | The database, an operator, or a managed service |
Fix: use StatefulSets for things with per-member identity or storage; prefer an operator or a managed database for production data; set readiness to mean "this member can serve"; keep terminationGracePeriodSeconds long enough for a clean flush; practise the forced-rollback path before you need it.
DaemonSet with node selectors and tolerations preview Important
In plain words: A DaemonSet runs one Pod on every node (or every node you select): log shippers, metrics agents, network and storage plugins.
Common misunderstanding: "A DaemonSet Pod runs on every node, including control-plane nodes." Control-plane nodes usually carry a NoSchedule taint; the DaemonSet runs there only if its Pods tolerate it. Conversely, the DaemonSet controller adds some tolerations automatically, so its Pods do land on nodes under memory or disk pressure.
Definition: "A DaemonSet ensures that all (or some) Nodes run a copy of a Pod. As nodes are added to the cluster, Pods are added to them." spec.template.spec.nodeSelector and node affinity restrict the nodes; tolerations let Pods onto tainted nodes. Automatically added tolerations include node.kubernetes.io/not-ready and unreachable (NoExecute), and disk-pressure, memory-pressure, pid-pressure, unschedulable (NoSchedule). Updates: RollingUpdate with maxUnavailable (default 1) and maxSurge (default 0; a surge "implies the possibility that the resources consumed by the daemonset on any given node can double"), or OnDelete.
New node node-9 joins the cluster
1 node registers with labels kubernetes.io/os=linux, topology.kubernetes.io/zone=b
2 DaemonSet controller: nodeSelector matches, taints tolerated -> create log-agent Pod for node-9
3 Pod is bound to node-9 directly via node affinity; it mounts hostPath /var/log
4 node drained: kubectl drain needs --ignore-daemonsets; the controller would recreate the Pod on the same node anywayReal scenarios: Fluent Bit or Fluentd shipping /var/log/containers; the Prometheus node exporter; the CNI plugin (Cilium, Calico) and CSI node plugins; a GPU device plugin only on nodes labelled for GPUs.
| Component | DaemonSet? | Why |
|---|---|---|
| Log / metrics agent | Yes | One per node, reads node files |
| CNI, kube-proxy, CSI node plugin | Yes (usually) | Configures the node itself |
| Ingress controller | Sometimes | DaemonSet with host ports on edge nodes, or a Deployment behind a LoadBalancer |
| Application services | No | Scale with load, not with node count |
Fix: select nodes explicitly (nodeSelector), add only the tolerations you mean, set requests (they are reserved on every node), and prefer maxUnavailable: 1 for agents that are cheap to restart; scheduling details are in Resources, Scheduling & Autoscaling.
Job: completions, parallelism, backoffLimit, activeDeadlineSeconds, ttlSecondsAfterFinished, indexed Job, podFailurePolicy Must-know
In plain words: A Job runs Pods until a number of them have succeeded, retries failures up to a limit, and then stops. It is for work that finishes: a migration, an export, a batch of images to resize.
Common misunderstanding: "A Job runs my command exactly once." It runs it until it succeeds the required number of times, and a Pod can run more than once (a node failure, a retry after OnFailure, a Pod replaced while the old one is still terminating). The CronJob docs say it plainly for scheduled Jobs: "the Jobs that you define should be idempotent". A migration that is not safe to run twice needs its own lock.
Definition:
- Completions and parallelism. A non-parallel Job leaves both unset (one Pod). A fixed completion count Job sets
.spec.completions; "You can set.spec.parallelism, or leave it unset and it will default to 1." A work-queue Job leavescompletionsunset and setsparallelism; the Pods coordinate through the queue. - Completion mode.
NonIndexed(default) orIndexed: "the Pods of a Job get an associated completion index from 0 to.spec.completions-1", available as the env variableJOB_COMPLETION_INDEX, an annotation, a label and the hostname. - Retries. "The
.spec.backoffLimitis set by default to 6"; failed Pods are recreated with an "exponential back-off delay (10s, 20s, 40s ...) capped at ten minutes". For Indexed Jobs,backoffLimitPerIndexcounts per index andmaxFailedIndexesfails the whole Job early (GA in v1.33). - Deadlines and cleanup. "Once a Job reaches
activeDeadlineSeconds, all of its running Pods are terminated and the Job status will becometype: Failedwithreason: DeadlineExceeded", and it "takes precedence over its.spec.backoffLimit".ttlSecondsAfterFinishedlets the TTL controller delete the finished Job and its Pods; the docs recommend setting it because directly created Jobs otherwise leave Pods behind after deletion. - Pod failure policy (GA in v1.31). Rules evaluated in order, each with an
action:FailJob("the Pod's job should be marked as Failed and all running Pods should be terminated"),Ignore(do not count towardbackoffLimit),Count(default handling) andFailIndex(with per-index backoff); conditionsonExitCodes(In/NotIn, optionalcontainerName) oronPodConditions(typicallyDisruptionTarget). It requiresrestartPolicy: Never. - Related:
successPolicyfor Indexed Jobs (GA v1.33),podReplacementPolicy(Failedwaits for a Pod to be fully terminated before creating its replacement; GA v1.34),suspend.
Indexed Job orders-export: completions 8, parallelism 4, backoffLimitPerIndex 2
1 Pods for indexes 0,1,2,3 start (JOB_COMPLETION_INDEX=0..3)
2 index 1 exits 0 -> index 4 starts; index 2 exits 1 -> retry 1 of 2 (a third failure would fail index 2)
3 index 5 exits 42 -> podFailurePolicy FailIndex: index 5 failed, no retry
4 a node drain evicts index 6 -> DisruptionTarget -> Ignore: recreated, not counted
5 all other indexes succeed -> Job Failed (FailedIndexes: 5), 7 of 8 shards exportedReal scenarios: php artisan migrate --force as a Job per release, not an init container; an export split into shards by JOB_COMPLETION_INDEX; a known "bad input" exit code that should fail fast instead of burning six retries; Jobs piling up in the namespace until ttlSecondsAfterFinished is set.
| Pattern | Settings | Fits |
|---|---|---|
| Single run | completions/parallelism unset, backoffLimit small | Migrations, one-off fixes |
| Fixed count | completions: N, parallelism: M | N independent tasks |
| Indexed | completionMode: Indexed, completions: N | Static sharding, per-index retries |
| Work queue | parallelism: M, no completions | Consumers that exit when the queue is empty |
| Laravel queue | Not a Job: a Deployment of queue:work | Continuous work (Laravel) |
Fix: always set activeDeadlineSeconds and ttlSecondsAfterFinished; use restartPolicy: Never with a podFailurePolicy that fails fast on known-permanent exit codes and ignores disruptions; make every Pod's work idempotent; for continuous queues use workers in a Deployment, as Competing Consumers & Scaling explains.
CronJob: schedule, concurrencyPolicy, startingDeadlineSeconds, missed runs Important
In plain words: A CronJob creates a Job on a cron schedule. It decides what to do when the previous run is still going and how late a run may still start.
Common misunderstanding: "A CronJob runs exactly once per tick." The docs: "A CronJob creates a Job object approximately once per execution time of its schedule ... there are certain circumstances where two Jobs might be created, or no Job might be created." Missed ticks are not replayed one by one either: after a long controller outage at most the most recent one runs.
Definition: .spec.schedule (cron syntax, 0 3 * * 1 = Mondays 03:00) interpreted in .spec.timeZone (stable v1.27; otherwise the kube-controller-manager's local zone; CRON_TZ/TZ inside the schedule are rejected). .spec.concurrencyPolicy: Allow (default), Forbid ("the CronJob skips the new Job run" while the previous one runs) or Replace (replaces the running Job). .spec.startingDeadlineSeconds: a missed run may start up to that many seconds late; with a value below 10 "the CronJob may not be scheduled", because "the CronJob controller checks things every 10 seconds". More than 100 missed schedules produce the event too many missed start times and still start "a Job for the most recent missed schedule". .spec.suspend pauses new runs (suspended ticks count as missed). History: successfulJobsHistoryLimit default 3, failedJobsHistoryLimit default 1. Changes apply only to Jobs created after the change.
Laravel scheduler CronJob, schedule "* * * * *", Forbid, startingDeadlineSeconds 30
10:00:00 Job shop-scheduler-29123460 created -> schedule:run starts
10:00:52 schedule:run still running (a slow task without runInBackground)
10:01:00 tick: previous Job active -> Forbid -> skipped (counts as missed)
10:01:20 previous Job finishes; within the 30 s deadline -> a Job for 10:01 starts now
10:02:00 normal tickReal scenarios: a backup at 02:00 that sometimes runs past 03:00 needs Forbid; a report that must not start more than an hour late needs startingDeadlineSeconds: 3600; a cluster whose controller manager runs in UTC fires an "08:00" report at 08:00 UTC unless timeZone is set; the Laravel scheduler as a per-minute CronJob spawns 1,440 Jobs a day, which history limits and TTL must clean up.
| Need | Setting |
|---|---|
| Never two at once | concurrencyPolicy: Forbid |
| Newest run wins | concurrencyPolicy: Replace |
| Late run acceptable for 1 h | startingDeadlineSeconds: 3600 |
| Local business time | timeZone: "Europe/Berlin" (any tz database name) |
| Pause during an incident | kubectl patch cronjob X -p '{"spec":{"suspend":true}}' |
| Run now, out of schedule | kubectl create job --from=cronjob/X X-manual-1 |
Fix: make every scheduled Job idempotent; set concurrencyPolicy, startingDeadlineSeconds (at least tens of seconds), timeZone and history limits explicitly; for the Laravel scheduler choose between this and a schedule:work Deployment in Choosing.
PodDisruptionBudget Important
In plain words: A PDB tells Kubernetes "during planned maintenance, never take more than X of these Pods away at once". Node drains and cluster autoscalers ask before evicting.
Common misunderstanding: "A PDB protects my rollout." It does not: "workload resources (such as Deployment and StatefulSet) are not limited by PDBs when doing rolling upgrades." It also does not stop involuntary disruptions (a node crash) or direct deletes ("deleting deployments or pods bypasses Pod Disruption Budgets"). It limits voluntary evictions through the Eviction API.
Definition: policy/v1 (stable v1.21). One of minAvailable or maxUnavailable ("You can specify only one"), as a number or a percentage (percentages are rounded up), and a selector. kubectl drain and the cluster autoscaler call the Eviction API, which refuses an eviction that would violate the budget; evicted Pods are terminated gracefully, "honoring the terminationGracePeriodSeconds". unhealthyPodEvictionPolicy: AlwaysAllow (GA v1.31) lets drains evict Pods that are not healthy anyway; the docs recommend it, since the default waits for the application Pods to become healthy. A budget of maxUnavailable: 0 (or minAvailable equal to the replica count) blocks every voluntary eviction.
kubectl drain node-3 (shop-web: 3 replicas, PDB minAvailable 2; two shop-web Pods on node-3)
1 evict shop-web-a -> allowed (3 healthy -> 2), Pod terminates gracefully, ReplicaSet creates a replacement elsewhere
2 evict shop-web-b -> 429 Too Many Requests (would leave 1 < 2); drain retries
3 replacement becomes Ready on node-5 -> 3 healthy again -> eviction of shop-web-b allowed
4 node-3 empty (except DaemonSet Pods) -> maintenance proceedsReal scenarios: a managed node-pool upgrade (EKS, GKE, AKS) that hangs for an hour because a PDB with one replica and minAvailable: 1 can never be satisfied; a quorum system (ZooKeeper, etcd) with minAvailable equal to quorum; a Deployment with 2 replicas both on the drained node and maxUnavailable: 1, which drains one Pod at a time.
| Workload | Suggested budget |
|---|---|
| Stateless, many replicas | maxUnavailable: 1 or a percentage |
| Web tier with a capacity floor | minAvailable: N below replicas |
| Quorum (3 or 5 members) | minAvailable: quorum or maxUnavailable: 1 |
| Single replica | Usually no PDB (or accept a blocked drain and handle it by hand) |
Fix: a PDB for every multi-replica service users depend on, never one that forbids all evictions, unhealthyPodEvictionPolicy: AlwaysAllow, and replicas spread across nodes so a single drain cannot hit the floor.
HorizontalPodAutoscaler preview and Pod topology spread preview Good to know
In plain words: An HPA changes a Deployment's replicas from metrics; topology spread constraints keep replicas apart across zones and nodes. Both are taught in Resources, Scheduling & Autoscaling; here is what they change about workload manifests.
Common misunderstanding: "Keep replicas: 3 in the manifest and add an HPA." Every apply (or GitOps sync) resets replicas to 3 and fights the HPA. When an HPA owns the count, remove replicas from the manifest (or ignore the field in the GitOps tool).
Definition: The HPA computes desiredReplicas = ceil[currentReplicas × (currentMetricValue / desiredMetricValue)], every 15 seconds by default, with a tolerance of 0.1 and a scale-down stabilisation window of 5 minutes; resource metrics come from metrics-server. CPU utilisation targets are percentages of the containers' requests. Scale to zero (minReplicas: 0) is beta behind HPAScaleToZero in v1.37. topologySpreadConstraints take maxSkew, topologyKey (for example topology.kubernetes.io/zone), whenUnsatisfiable (DoNotSchedule or ScheduleAnyway) and a labelSelector that should match the workload's own Pods.
orders-api: 3 Pods at 140% of requested CPU, target 70%
1 desired = ceil(3 x 140 / 70) = 6
2 HPA sets Deployment replicas 6 -> ReplicaSet creates 3 Pods (no new revision)
3 topology spread: the scheduler prefers zones with fewer orders-api Pods (maxSkew 1)
4 load drops: no scale-down until 5 minutes of lower recommendationsReal scenarios: an HPA on CPU for the Go service; KEDA scaling Laravel workers on Redis queue length; replicas all landing in one zone until a spread constraint is added.
| Tool | Scales on |
|---|---|
HPA autoscaling/v2 | CPU, memory, custom and external metrics |
| KEDA | Event sources (queues, streams, cron), creates HPAs |
| VPA | Requests of existing Pods (not replica count) |
| Cluster autoscaler / Karpenter | Nodes, when Pods are Pending |
Fix: set CPU requests, remove replicas when an HPA owns it, add a zone spread constraint to every multi-replica Deployment; the Go manifests include hpa.yaml as a starting point.
Services as the consumer of readiness (preview) Important
In plain words: A Service is a stable name and virtual IP in front of a changing set of Pods. Which Pods receive traffic is decided by its selector and by readiness.
Common misunderstanding: "The Service load-balances over every Pod with the label." Only over ready endpoints. A Pod that is Running but not Ready is in the EndpointSlice with ready: false and receives no regular traffic; a terminating Pod is listed with ready: false, serving (its real readiness) and terminating: true.
Definition: The EndpointSlice controller watches Pods matching the Service selector and writes their addresses with conditions; kube-proxy (or a CNI replacing it), Ingress controllers and Gateway API implementations read the slices. A headless Service (clusterIP: None) gets no virtual IP: "kube-proxy does not handle these Services, and there is no load balancing or proxying done by the platform"; DNS returns the Pod addresses, which is what a StatefulSet's per-Pod names rely on. Service types, kube-proxy modes, DNS, Ingress and Gateway API are covered in Kubernetes Networking.
EndpointSlice for Service orders-api during a rollout (conditions per endpoint)
10.1.7.23 ready=true serving=true terminating=false old Pod, in rotation
10.1.4.11 ready=false serving=true terminating=true old Pod, draining (preStop running)
10.1.5.40 ready=false serving=false terminating=false new Pod, readiness not yet passing
10.1.5.41 ready=true serving=true terminating=false new Pod, in rotationReal scenarios: kubectl get endpointslices -l kubernetes.io/service-name=orders-api empty because the selector has a typo; a readiness probe that never passes leaves the Service with zero ready endpoints and Nginx Ingress returns 503; a cloud load balancer that ignores serving drops a terminating Pod immediately.
| Consumer | Reads |
|---|---|
| kube-proxy (iptables, IPVS, nftables) | Ready endpoints (and serving terminating ones as a fallback) |
| Nginx Ingress, Gateway API controllers | EndpointSlices, ready endpoints |
| Cloud LB with Pod-IP targets | Its own health checks, plus readiness gates if enabled |
| Headless Service DNS | Pod addresses (ready ones by default) |
Fix: a readiness probe on every Pod behind a Service; selectors checked with kubectl get endpointslices; a preStop delay for the time the consumers take to notice a terminating endpoint.
php-fpm and Nginx: sidecar vs two containers vs one container Important
In plain words: Laravel on php-fpm needs a web server in front, because FPM speaks FastCGI, not HTTP. In Kubernetes you put Nginx in the same Pod (as a native sidecar or as a second app container), or switch to a single-process server such as FrankenPHP.
Common misunderstanding: "Two containers in containers is the same as a sidecar." With two regular containers, both receive their stop signal "at different times and in an arbitrary order", so Nginx can stop before FPM has returned its last responses (or FPM before Nginx stops forwarding), and they start in no particular order. Declaring Nginx as a native sidecar fixes the order: Nginx starts first and is stopped only after php-fpm has exited.
Definition: In the Laravel manifest Nginx is an entry in initContainers with restartPolicy: Always and the readiness probe (/up through Nginx and FastCGI, which tests both processes); php-fpm is the app container with a tcpSocket liveness probe, a preStop sleep and the image's STOPSIGNAL SIGQUIT; fastcgi_pass 127.0.0.1:9000 because they share the network namespace; process_control_timeout = 20s in a [global] FPM include, the "Time limit for child processes to wait for a reaction on signals from master" (documented default 0), so busy workers get time to finish after SIGQUIT: in fpm_process_ctl.c the master sends the children SIGQUIT, waits process_control_timeout, then escalates to SIGTERM and, a second later, SIGKILL. The sidecar docs name exactly this case: "if you have a web application that requires a local webserver, the local webserver is a sidecar and the web application itself is the app container."
shop-web Pod deleted (grace 45 s)
t=0 endpoint ready=false; php-fpm preStop sleep 10 s (Nginx and FPM keep serving)
t=10 SIGQUIT to php-fpm master: stop accepting, busy workers finish (<= 20 s)
t=18 php-fpm exits -> now the kubelet stops the Nginx sidecar: SIGQUIT = graceful shutdown
t=19 Nginx exits -> Pod gone, 26 s of the 45 s budget unusedReal scenarios: Nginx returning 502 during deploys because FPM died first (two regular containers, no preStop); an FPM pool cutting requests off on stop because process_control_timeout was left at 0 (the master sends SIGQUIT to its children and, when that timeout expires, escalates to SIGTERM and then SIGKILL, per fpm_process_ctl.c); static assets 404 because the Nginx image does not contain public/ (the image chapter's web target copies it).
| Model | Start order | Stop order | Images | Fits |
|---|---|---|---|---|
| Nginx native sidecar + php-fpm | Nginx, then FPM | FPM, then Nginx | 2 (web, app) | Kubernetes v1.29+ (stable v1.33) |
| Two regular containers | Undefined | Arbitrary, simultaneous | 2 | Older clusters; add preStop sleeps to both |
| Nginx Deployment + FPM Deployment | Independent | Independent | 2 | Rarely: FastCGI over the network, two scaling knobs to keep in step |
| FrankenPHP (with or without Octane) | One process | One process | 1 | New projects, fewer moving parts |
Fix: use the native sidecar layout when you stay on php-fpm; set process_control_timeout; keep preStop + FPM drain + Nginx drain below the grace period; consider FrankenPHP for a single container per Pod (the image chapter builds one).
Mechanics
The control loops: Deployment, ReplicaSet, scheduler, kubelet
No component "runs a Deployment". Each controller watches some objects and writes others, and the chain ends at the kubelet, the only actor that talks to the container runtime.
you: kubectl apply (Deployment, template hash 7d4b9c)
Deployment controller ─▶ ReplicaSet orders-api-7d4b9c (replicas per rollout arithmetic)
ReplicaSet controller ─▶ Pods with ownerReferences -> ReplicaSet, labels + pod-template-hash
scheduler ─▶ Pod.spec.nodeName = node-7 (binding)
kubelet on node-7 ─▶ CRI: sandbox, pull, init containers, sidecars, app containers, probes
kubelet ─▶ Pod status: phase, conditions, containerStatuses (ready, restartCount)
EndpointSlice ctrl ─▶ endpoints for Services whose selector matches, with ready/serving/terminating
Deployment controller ◀─ availableReplicas from ReplicaSets -> next rollout step, conditions, rollout statusOwnership (metadata.ownerReferences) is what makes kubectl delete deployment remove the ReplicaSets and Pods (cascading deletion) and what lets the PDB machinery find the controller behind a Pod. Job and CronJob follow the same pattern (CronJob → Job → Pods); a StatefulSet and a DaemonSet own their Pods directly and record revisions in ControllerRevision objects instead of ReplicaSets.
How a rollout decides its next step
The Deployment controller converts percentages first (maxSurge rounds up, maxUnavailable rounds down), then repeats two moves until the new ReplicaSet has replicas available Pods:
| Step | Rule | Example: replicas 10, maxSurge 25%, maxUnavailable 25% |
|---|---|---|
| Bounds | counted Pods ≤ replicas + maxSurge; available ≥ replicas − maxUnavailable; terminating Pods are not counted | 25% of 10 = 2.5: surge 3, unavailable 2; counted ≤ 13 (plus any still terminating), available ≥ 8 |
| Scale up | New RS may grow while counted Pods stay within the surge bound | New RS 0 → 3 |
| Scale down | Old RS may shrink while available stays ≥ min available | Old RS 10 → 8 |
| Wait | New Pods count only after Ready for minReadySeconds | Next steps follow readiness |
| Progress | Any step resets the progress timer; no progress for progressDeadlineSeconds → ProgressDeadlineExceeded | 600 s by default |
| Complete | New RS = replicas, all available, old RS = 0 | NewReplicaSetAvailable |
| replicas | maxSurge 25% (up) | maxUnavailable 25% (down) | Pods during rollout |
|---|---|---|---|
| 1 | 1 | 0 | 1–2 |
| 2 | 1 | 0 | 2–3 |
| 3 | 1 | 0 | 3–4 |
| 4 | 1 | 1 | 3–5 (the docs' example) |
| 10 | 3 | 2 | 8–13 |
These bounds exclude terminating Pods. The Deployment docs: "Kubernetes doesn't count terminating Pods when calculating the number of availableReplicas", so "the total resources consumed by the Deployment is more than replicas + maxSurge until the terminationGracePeriodSeconds of the terminating Pods expires." With a long grace period (the 110 s queue workers, the 45 s web Pods) budget node capacity, quotas and per-Pod licences for replicas + maxSurge plus the Pods still draining.
For a StatefulSet the arithmetic is simpler: one Pod at a time from the highest ordinal down (or up to maxUnavailable Pods with the beta field), waiting for Running and Ready (and minReadySeconds) after each, stopping at the partition.
What the kubelet does when a container is stopped
| # | Step | Who | Counts against the grace period? |
|---|---|---|---|
| 1 | Pod gets deletionTimestamp and deletionGracePeriodSeconds | API server | Starts it |
| 2 | Endpoint conditions change (ready false, terminating true) | EndpointSlice controller | In parallel |
| 3 | preStop hook (exec in container; httpGet or sleep by the kubelet) | kubelet | Yes |
| 4 | Stop signal to PID 1 (image STOPSIGNAL, default SIGTERM) | runtime | Yes |
| 5 | Wait for exit | kubelet | Yes |
| 6 | Sidecars: stop signal in reverse definition order after app containers exit | kubelet | Yes |
| 7 | Deadline: SIGKILL to every remaining process (+2 s once if preStop was still running) | runtime | End |
| 8 | Terminal phase, Pod object removed | kubelet, API server | After |
Liveness- and startup-probe kills use the same sequence for one container (preStop included), with the probe-level terminationGracePeriodSeconds if set. Evictions through the Eviction API honour the Pod's grace period; a node-pressure eviction by the kubelet may not.
Knobs
| Knob | Object | Default | Notes |
|---|---|---|---|
restartPolicy | Pod | Always | Deployments allow only Always; Jobs OnFailure/Never |
| Restart backoff | kubelet | 10 s doubling to 300 s, reset after 10 min | KubeletCrashLoopBackOffMax (beta v1.35) per node |
terminationGracePeriodSeconds | Pod / probe | 30 | Covers preStop + stop; never 0 in StatefulSets |
lifecycle.preStop.sleep.seconds | container | none | Stable v1.34; no shell needed |
Probe initialDelaySeconds / periodSeconds / timeoutSeconds | probe | 0 / 10 / 1 | Minimums 0 / 1 / 1 |
Probe failureThreshold / successThreshold | probe | 3 / 1 | successThreshold 1 for liveness, startup |
imagePullPolicy | container | derived from tag/digest | Set once at creation |
strategy.rollingUpdate.maxSurge / maxUnavailable | Deployment | 25% / 25% | Up / down rounding; not both 0 |
minReadySeconds | Deployment, StatefulSet, DaemonSet | 0 | Ready this long = available |
progressDeadlineSeconds | Deployment | 600 | Must exceed minReadySeconds |
revisionHistoryLimit | Deployment, StatefulSet, DaemonSet | 10 | 0 disables rollback |
podManagementPolicy | StatefulSet | OrderedReady | Parallel for scaling speed |
updateStrategy.rollingUpdate.partition | StatefulSet | 0 | Ordinals ≥ partition update |
updateStrategy.rollingUpdate.maxUnavailable | StatefulSet / DaemonSet | 1 / 1 | StatefulSet field beta, on in v1.37 |
updateStrategy.rollingUpdate.maxSurge | DaemonSet | 0 | Old and new on one node |
backoffLimit | Job | 6 | backoffLimitPerIndex for Indexed |
activeDeadlineSeconds | Job | none | Wins over backoffLimit |
ttlSecondsAfterFinished | Job | none | TTL controller deletes Job + Pods |
concurrencyPolicy | CronJob | Allow | Forbid, Replace |
startingDeadlineSeconds | CronJob | none | Below 10 s may never schedule |
successfulJobsHistoryLimit / failedJobsHistoryLimit | CronJob | 3 / 1 | |
unhealthyPodEvictionPolicy | PDB | IfHealthyBudget | AlwaysAllow recommended |
process_control_timeout | php-fpm [global] | 0 | "Time limit for child processes to wait for a reaction on signals from master" |
--timeout / retry_after | Laravel queue | 60 / 90 (Redis) | --timeout several seconds shorter than retry_after |
Error messages and statuses you will actually see
| Message / status | Meaning | Fix |
|---|---|---|
CrashLoopBackOff (STATUS) | Container keeps exiting; kubelet is waiting before the next restart | kubectl logs --previous, describe Last State |
Liveness probe failed: ... then Container ... failed liveness probe, will be restarted | Liveness killed the container | Startup probe, looser thresholds, cheaper endpoint |
Readiness probe failed: HTTP probe failed with statuscode: 503 | Pod out of the Service | Expected while warming or draining; otherwise check dependencies |
ImagePullBackOff / ErrImagePull | Tag missing, registry auth, rate limit | Fix the reference or imagePullSecrets |
OOMKilled, exit code 137 | Memory limit hit (137 = 128 + SIGKILL) | Raise the limit or fix the leak |
| Exit code 143 | Process ended by SIGTERM (128 + 15) without handling it | Handle the signal, exit 0 after drain |
Init:CrashLoopBackOff, Init:0/2 | An init container fails or is still running | Logs of the init container (-c name) |
error: deployment "x" exceeded its progress deadline | rollout status gave up; Progressing=False | Fix the new Pods or rollout undo |
field is immutable (on spec.selector) | Selector changed | Delete and recreate, or keep the selector |
too many missed start times. Set or decrease .spec.startingDeadlineSeconds or check clock skew | CronJob controller missed > 100 schedules | Set startingDeadlineSeconds |
Cannot evict pod as it would violate the pod's disruption budget. | Drain blocked by a PDB | Wait, add replicas, or fix the budget |
BackoffLimitExceeded / DeadlineExceeded (Job reason) | Retries or time used up | Logs of failed Pods; podFailurePolicy |
Go
The Go service is the one from Images & Dockerfiles, reshaped around the three probe questions and the termination budget: /livez, /startupz, /readyz, a readiness flip and an optional in-app drain delay on SIGTERM, and a Shutdown bounded by SHUTDOWN_TIMEOUT. It is stdlib only (Go 1.22 method patterns such as GET /livez, signal.NotifyContext from Go 1.16).
Before
The manifest many first deployments start with: a moving tag, no startup or readiness probe, a liveness probe that checks the database, and an app that closes its listener the instant SIGTERM arrives.
# Before: works in the demo, drops requests and restarts the fleet in production
apiVersion: apps/v1
kind: Deployment
metadata:
name: orders-api
spec:
replicas: 3
selector:
matchLabels:
app: orders-api
version: "1.4" # in the immutable selector: every release needs a new Deployment
template:
metadata:
labels:
app: orders-api
version: "1.4"
spec:
containers:
- name: api
image: ghcr.io/acme/orders-api:latest # imagePullPolicy becomes Always; versions mix
livenessProbe:
httpGet:
path: /health?check=db # DB outage -> every replica restarted
port: 8080
initialDelaySeconds: 60 # slow on every start, still too short sometimes
# no readinessProbe: traffic as soon as the process starts
# no preStop, app calls os.Exit on SIGTERM: in-flight requests droppedAfter
The application side: three probe endpoints with different meanings, warm-up after the listener is open, and the SIGTERM sequence (readiness off, optional drain delay, bounded Shutdown). The tests cover startup gating, a failing dependency that fails readiness but not liveness, a drain with a request in flight (new requests still served during the delay, nil return) and a request that outlives the timeout (context.DeadlineExceeded).
// Command orders-api is the Go service used as the worked Deployment in the
// Kubernetes Workloads chapter. It shows the application side of a Pod:
// - /livez liveness: "this process can still make progress"; it never
// checks dependencies, so a database outage does not restart every Pod;
// - /startupz startup: 503 until warm-up has finished, then 200;
// - /readyz readiness: 200 only when started, not draining and the
// dependencies answer; 503 otherwise;
// - on SIGTERM it marks itself not ready, optionally keeps serving for
// DRAIN_DELAY (for clusters without a preStop sleep), then calls
// http.Server.Shutdown bounded by SHUTDOWN_TIMEOUT.
//
// The budget rule: preStop sleep + DRAIN_DELAY + SHUTDOWN_TIMEOUT must stay
// below terminationGracePeriodSeconds, because the grace period counts from
// the moment the Pod is marked for deletion, preStop included.
package main
import (
"context"
"encoding/json"
"errors"
"log/slog"
"net"
"net/http"
"os"
"os/signal"
"sync/atomic"
"syscall"
"time"
)
// Config holds the knobs that the Deployment sets through env variables.
type Config struct {
Addr string // listen address, ":8080" by default
Warmup time.Duration // simulated start-up work (cache fill, migrations check)
DrainDelay time.Duration // keep serving after SIGTERM before closing the listener
ShutdownTimeout time.Duration // upper bound for http.Server.Shutdown
}
// Health is the state the three probe endpoints read.
type Health struct {
started atomic.Bool
draining atomic.Bool
// CheckDeps is called by /readyz only. Nil means "no dependencies".
CheckDeps func(ctx context.Context) error
}
func main() {
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
cfg := Config{
Addr: ":" + env("PORT", "8080"),
Warmup: envDuration("WARMUP", 0),
DrainDelay: envDuration("DRAIN_DELAY", 0),
ShutdownTimeout: envDuration("SHUTDOWN_TIMEOUT", 20*time.Second),
}
// SIGTERM is what the kubelet asks the runtime to send (unless the image
// sets another STOPSIGNAL); SIGINT is Ctrl-C on a laptop.
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
defer stop()
ln, err := net.Listen("tcp", cfg.Addr)
if err != nil {
logger.Error("listen", "err", err)
os.Exit(1)
}
h := &Health{}
if err := Serve(ctx, ln, NewMux(h), h, cfg, logger); err != nil {
logger.Error("exit", "err", err)
os.Exit(1)
}
}
// NewMux wires the probe endpoints and one business route.
func NewMux(h *Health) *http.ServeMux {
mux := http.NewServeMux()
mux.HandleFunc("GET /livez", func(w http.ResponseWriter, r *http.Request) {
// Keep liveness cheap and local: a small body (the kubelet reads at
// most 10 KiB) and no calls to the database or other services.
w.Write([]byte("ok\n"))
})
mux.HandleFunc("GET /startupz", func(w http.ResponseWriter, r *http.Request) {
if !h.started.Load() {
http.Error(w, "starting", http.StatusServiceUnavailable)
return
}
w.Write([]byte("started\n"))
})
mux.HandleFunc("GET /readyz", func(w http.ResponseWriter, r *http.Request) {
switch {
case !h.started.Load():
http.Error(w, "starting", http.StatusServiceUnavailable)
return
case h.draining.Load():
http.Error(w, "draining", http.StatusServiceUnavailable)
return
}
if h.CheckDeps != nil {
// Stay inside the probe's timeoutSeconds (1 s by default).
ctx, cancel := context.WithTimeout(r.Context(), 800*time.Millisecond)
defer cancel()
if err := h.CheckDeps(ctx); err != nil {
http.Error(w, "dependency: "+err.Error(), http.StatusServiceUnavailable)
return
}
}
w.Write([]byte("ready\n"))
})
mux.HandleFunc("GET /orders/{id}", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"id": r.PathValue("id"), "status": "paid"})
})
return mux
}
// Serve runs handler on ln until ctx is cancelled (SIGTERM), then drains.
// It returns nil after a clean drain, or the Shutdown error
// (context.DeadlineExceeded) when requests outlive ShutdownTimeout.
func Serve(ctx context.Context, ln net.Listener, handler http.Handler, h *Health, cfg Config, logger *slog.Logger) error {
srv := &http.Server{
Handler: handler,
ReadHeaderTimeout: 5 * time.Second,
}
errc := make(chan error, 1)
go func() { errc <- srv.Serve(ln) }()
logger.Info("listening", "addr", ln.Addr().String())
// Warm-up runs after the listener is open, so /startupz can answer 503
// (instead of "connection refused") while it is in progress.
go func() {
select {
case <-time.After(cfg.Warmup):
h.started.Store(true)
logger.Info("started")
case <-ctx.Done():
}
}()
select {
case err := <-errc:
return err // the listener failed; nothing to drain
case <-ctx.Done():
}
// 1. Fail readiness. In Kubernetes the endpoint is already marked
// not ready because the Pod is terminating; this matters for other
// load balancers that only look at /readyz.
h.draining.Store(true)
logger.Info("draining", "delay", cfg.DrainDelay.String())
// 2. Keep accepting connections while kube-proxy, ingress controllers and
// cloud load balancers catch up with the endpoint change.
time.Sleep(cfg.DrainDelay)
// 3. Close the listener, finish in-flight requests, bounded in time.
sctx, cancel := context.WithTimeout(context.Background(), cfg.ShutdownTimeout)
defer cancel()
err := srv.Shutdown(sctx)
if serr := <-errc; serr != nil && !errors.Is(serr, http.ErrServerClosed) {
return serr
}
if err != nil {
return err
}
logger.Info("stopped")
return nil
}
func env(key, def string) string {
if v := os.Getenv(key); v != "" {
return v
}
return def
}
func envDuration(key string, def time.Duration) time.Duration {
if v := os.Getenv(key); v != "" {
if d, err := time.ParseDuration(v); err == nil {
return d
}
}
return def
}package main
import (
"context"
"errors"
"io"
"log/slog"
"net"
"net/http"
"net/http/httptest"
"testing"
"time"
)
// testClient opens one connection per request. With keep-alives the
// transport can dial a spare connection that never carries a request; the
// server sees it as StateNew, and Shutdown waits for such connections (up to
// 5 s in net/http) before treating them as idle, which made the drain test
// flaky against its 2 s timeout.
var testClient = &http.Client{Transport: &http.Transport{DisableKeepAlives: true}}
func status(t *testing.T, h http.Handler, path string) int {
t.Helper()
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, path, nil))
return rec.Code
}
// Before warm-up: alive, not started, not ready. After: all three 200.
func TestProbesDuringStartup(t *testing.T) {
h := &Health{}
mux := NewMux(h)
if got := status(t, mux, "/livez"); got != http.StatusOK {
t.Fatalf("livez before start = %d, want 200", got)
}
for _, p := range []string{"/startupz", "/readyz"} {
if got := status(t, mux, p); got != http.StatusServiceUnavailable {
t.Fatalf("%s before start = %d, want 503", p, got)
}
}
h.started.Store(true)
for _, p := range []string{"/livez", "/startupz", "/readyz"} {
if got := status(t, mux, p); got != http.StatusOK {
t.Fatalf("%s after start = %d, want 200", p, got)
}
}
}
// A failing dependency makes the Pod unready but must not fail liveness,
// otherwise a database outage would restart every replica at once.
func TestDependencyFailsReadinessOnly(t *testing.T) {
h := &Health{CheckDeps: func(context.Context) error { return errors.New("db down") }}
h.started.Store(true)
mux := NewMux(h)
if got := status(t, mux, "/readyz"); got != http.StatusServiceUnavailable {
t.Fatalf("readyz with failing dependency = %d, want 503", got)
}
if got := status(t, mux, "/livez"); got != http.StatusOK {
t.Fatalf("livez with failing dependency = %d, want 200", got)
}
}
// startServer runs Serve on 127.0.0.1:0 with extra test routes and returns
// the base URL, the cancel func standing in for SIGTERM, and Serve's result.
func startServer(t *testing.T, cfg Config, extra func(*http.ServeMux)) (string, context.CancelFunc, <-chan error) {
t.Helper()
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
h := &Health{}
mux := NewMux(h)
if extra != nil {
extra(mux)
}
ctx, cancel := context.WithCancel(context.Background())
done := make(chan error, 1)
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
go func() { done <- Serve(ctx, ln, mux, h, cfg, logger) }()
base := "http://" + ln.Addr().String()
deadline := time.Now().Add(2 * time.Second)
for {
resp, err := testClient.Get(base + "/readyz")
if err == nil {
resp.Body.Close()
if resp.StatusCode == http.StatusOK {
break
}
}
if time.Now().After(deadline) {
t.Fatal("server never became ready")
}
time.Sleep(10 * time.Millisecond)
}
return base, cancel, done
}
// SIGTERM sequence: readiness fails at once, new requests are still served
// during DrainDelay, the in-flight request completes, Serve returns nil.
func TestServeDrainsOnSIGTERM(t *testing.T) {
cfg := Config{DrainDelay: 300 * time.Millisecond, ShutdownTimeout: 2 * time.Second}
base, cancel, done := startServer(t, cfg, func(m *http.ServeMux) {
m.HandleFunc("GET /slow", func(w http.ResponseWriter, r *http.Request) {
time.Sleep(500 * time.Millisecond)
w.Write([]byte("finished"))
})
})
inflight := make(chan int, 1)
go func() {
resp, err := testClient.Get(base + "/slow")
if err != nil {
inflight <- -1
return
}
resp.Body.Close()
inflight <- resp.StatusCode
}()
time.Sleep(50 * time.Millisecond) // let /slow start
cancel() // the kubelet's SIGTERM
time.Sleep(50 * time.Millisecond)
resp, err := testClient.Get(base + "/readyz")
if err != nil {
t.Fatalf("readyz during drain: %v", err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusServiceUnavailable {
t.Fatalf("readyz during drain = %d, want 503", resp.StatusCode)
}
resp, err = testClient.Get(base + "/orders/42")
if err != nil {
t.Fatalf("new request during drain delay was refused: %v", err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Fatalf("orders during drain = %d, want 200", resp.StatusCode)
}
if code := <-inflight; code != http.StatusOK {
t.Fatalf("in-flight request = %d, want 200", code)
}
select {
case err := <-done:
if err != nil {
t.Fatalf("Serve returned %v, want nil", err)
}
case <-time.After(3 * time.Second):
t.Fatal("Serve did not return")
}
}
// A request that outlives ShutdownTimeout makes Serve return
// context.DeadlineExceeded; in a Pod this is the moment SIGKILL would win.
func TestServeShutdownTimeout(t *testing.T) {
release := make(chan struct{})
t.Cleanup(func() { close(release) })
cfg := Config{ShutdownTimeout: 200 * time.Millisecond}
base, cancel, done := startServer(t, cfg, func(m *http.ServeMux) {
m.HandleFunc("GET /stuck", func(w http.ResponseWriter, r *http.Request) {
<-release
})
})
go func() {
resp, err := testClient.Get(base + "/stuck")
if err == nil {
resp.Body.Close()
}
}()
time.Sleep(50 * time.Millisecond)
start := time.Now()
cancel()
select {
case err := <-done:
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("Serve returned %v, want context.DeadlineExceeded", err)
}
if el := time.Since(start); el > time.Second {
t.Fatalf("Serve took %v, want about 200ms", el)
}
case <-time.After(3 * time.Second):
t.Fatal("Serve did not return")
}
}
func TestEnvDuration(t *testing.T) {
t.Setenv("DRAIN_DELAY", "7s")
if got := envDuration("DRAIN_DELAY", 0); got != 7*time.Second {
t.Fatalf("envDuration = %v, want 7s", got)
}
t.Setenv("DRAIN_DELAY", "seven")
if got := envDuration("DRAIN_DELAY", time.Second); got != time.Second {
t.Fatalf("invalid value: envDuration = %v, want default 1s", got)
}
}module academy/kubernetes-workloads
go 1.24The Deployment: digest-ready image reference, explicit selector, maxSurge 1 / maxUnavailable 0, minReadySeconds, progressDeadlineSeconds, the three probes with their worst-case times in comments, the preStop sleep action (the image is distroless), a non-root security context, a zone spread constraint and requests.
# orders-api: the Go service from go-service/ as a Deployment.
# Probes: startup gates the other two; liveness is local only; readiness
# includes dependencies. Termination budget (all inside the 30 s grace period):
# preStop sleep 5 s + SHUTDOWN_TIMEOUT 20 s = 25 s < 30 s
apiVersion: apps/v1
kind: Deployment
metadata:
name: orders-api
labels:
app.kubernetes.io/name: orders-api
app.kubernetes.io/part-of: shop
spec:
replicas: 3 # remove this line when an HPA owns the replica count
revisionHistoryLimit: 5 # old ReplicaSets kept for `kubectl rollout undo` (default 10)
minReadySeconds: 5 # Ready for 5 s before a Pod counts as available
progressDeadlineSeconds: 300 # report ProgressDeadlineExceeded after 5 min (default 600)
selector:
matchLabels: # immutable after creation; must match the template labels
app.kubernetes.io/name: orders-api
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1 # at most replicas + 1 counted Pods; terminating Pods come on top
maxUnavailable: 0 # never below replicas available Pods
template:
metadata:
labels:
app.kubernetes.io/name: orders-api
app.kubernetes.io/part-of: shop
app.kubernetes.io/version: "1.4.2"
spec:
terminationGracePeriodSeconds: 30
securityContext:
runAsNonRoot: true
runAsUser: 65532 # distroless "nonroot" user from the image chapter
topologySpreadConstraints: # preview; full treatment in the scheduling chapter
- maxSkew: 1
topologyKey: topology.kubernetes.io/zone
whenUnsatisfiable: ScheduleAnyway
labelSelector:
matchLabels:
app.kubernetes.io/name: orders-api
containers:
- name: api
# Pin by digest in production: ghcr.io/acme/orders-api:1.4.2@sha256:<digest from CI>
image: ghcr.io/acme/orders-api:1.4.2
imagePullPolicy: IfNotPresent # the default for a non-latest tag, written out
ports:
- name: http
containerPort: 8080
env:
- name: PORT
value: "8080"
- name: SHUTDOWN_TIMEOUT
value: "20s"
- name: DRAIN_DELAY # 0: the preStop sleep below does the waiting
value: "0s"
resources: # preview; sizing is in the scheduling chapter
requests:
cpu: 100m
memory: 64Mi
limits:
memory: 128Mi
startupProbe: # up to 30 x 2 s = 60 s to warm up
httpGet:
path: /startupz
port: http
periodSeconds: 2
failureThreshold: 30
livenessProbe: # restart after 3 x 10 s of a wedged process
httpGet:
path: /livez
port: http
periodSeconds: 10
timeoutSeconds: 1
failureThreshold: 3
readinessProbe: # out of the Service after 2 x 5 s of failures
httpGet:
path: /readyz
port: http
periodSeconds: 5
timeoutSeconds: 1
failureThreshold: 2
successThreshold: 1
lifecycle:
preStop:
# The image is distroless (no shell, no sleep binary), so use the
# kubelet's sleep action (stable since v1.34) rather than exec.
sleep:
seconds: 5
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true# The consumer of readiness: only Ready, non-terminating Pods matched by the
# selector appear as ready endpoints in this Service's EndpointSlices.
apiVersion: v1
kind: Service
metadata:
name: orders-api
labels:
app.kubernetes.io/name: orders-api
spec:
selector:
app.kubernetes.io/name: orders-api
ports:
- name: http
port: 80
targetPort: http# Voluntary evictions (kubectl drain, node upgrades, cluster autoscaler) may
# take at most one orders-api Pod at a time. Rolling updates are NOT limited
# by this budget; the Deployment's maxUnavailable controls those.
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: orders-api
spec:
maxUnavailable: 1 # only one of maxUnavailable / minAvailable
unhealthyPodEvictionPolicy: AlwaysAllow # do not let crash-looping Pods block a drain
selector:
matchLabels:
app.kubernetes.io/name: orders-api# Preview only: metrics, behaviour and tuning are in the scheduling and
# autoscaling chapter. Needs metrics-server (or another metrics API provider)
# and CPU requests on the containers (set in deployment.yaml).
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: orders-api
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: orders-api
minReplicas: 3
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70The Go angle
- Two ways to wait for the traffic layer. The manifest uses
lifecycle.preStop.sleep(5 s) and setsDRAIN_DELAY=0s; on clusters or platforms without the sleep action, setDRAIN_DELAY=5sand drop the hook. Either way the delay happens beforeShutdowncloses the listener, which is what prevents connection-refused errors during endpoint removal; flipping/readyzto 503 alone does not, because the endpoint is already marked not ready by the deletion itself. - Budget arithmetic.
preStop5 s +SHUTDOWN_TIMEOUT20 s = 25 s, belowterminationGracePeriodSeconds30 s. Raise the grace period if any request (a report download, a long poll) can take longer, and keepReadHeaderTimeoutand handler timeouts belowSHUTDOWN_TIMEOUT. Shutdownis not the whole story. It "does not attempt to close nor wait for hijacked connections such as WebSockets"; registersrv.RegisterOnShutdownto tell long-lived connections to go away, and drain background workers (consumers, tickers) with the same context.- Liveness stays local.
/livezwrites a constant; it would fail only if the HTTP server cannot schedule a handler at all. Readiness gets the dependency check, with its own timeout (800 ms) inside the probe'stimeoutSecondsof 1 s. - Signals.
signal.NotifyContext(ctx, syscall.SIGTERM, syscall.SIGINT)turns the stop signal into context cancellation; it works because the distroless image's exec-formENTRYPOINTmakes the binary PID 1. Signal handling in depth is in OS Processes, Signals & Graceful Shutdown. - gRPC services. Register
google.golang.org/grpc/healthand use agrpcprobe on a numeric port; set the serving status toNOT_SERVINGon SIGTERM beforeGracefulStop, which "stops the server from accepting new connections and RPCs and blocks until all the pending RPCs are finished" (bound it with a timer andStop). - Connections that never sent a request.
Shutdowntreats aStateNewconnection as idle only after 5 s ("treat StateNew connections as if they're idle if we haven't read the first request's header in over 5 seconds", inserver.go); a client or proxy that pre-opens connections can therefore hold a drain for up to 5 s. KeepSHUTDOWN_TIMEOUTwell above that. The drain test uses a client without keep-alives for exactly this reason (it was flaky with spare pooled connections). - Tests without a cluster. Listening on
127.0.0.1:0and cancelling a context stands in for SIGTERM; the Lab also sends a real SIGTERM to the built binary.
Laravel
The Laravel side reuses the two images from Images & Dockerfiles: shop-app (php-fpm with the code, STOPSIGNAL SIGQUIT inherited from php:8.4-fpm) and shop-web (Nginx with public/). One image, several processes: the web tier, the queue workers, the scheduler and the migration each get their own controller.
Before
The single "do everything" Deployment that a VM setup translates into: Supervisor inside the container running FPM, Nginx, queue:work and cron, migrations at start, and three replicas.
# Before: one container, four processes, three replicas
apiVersion: apps/v1
kind: Deployment
metadata:
name: shop
spec:
replicas: 3 # 3 schedulers -> every scheduled task runs 3 times
selector:
matchLabels: {app: shop}
template:
metadata:
labels: {app: shop}
spec:
containers:
- name: shop
image: ghcr.io/acme/shop:latest
# supervisord starts php-fpm, nginx, queue:work and cron (schedule:run);
# supervisord is PID 1, so SIGTERM never reaches the queue worker as intended
command: ["sh", "-c", "php artisan migrate --force && supervisord -n"] # 3 Pods migrate at once
ports:
- containerPort: 80
# no probes, default 30 s grace: a 5-minute import job is killed on every deployAfter
The web tier: Nginx as a native sidecar in front of php-fpm, the shared-namespace FastCGI address, the FPM process_control_timeout include, readiness through /up, and a termination budget that lets FPM finish before Nginx stops.
# shop-web: Laravel behind Nginx in ONE Pod, built from the two image targets of
# the image chapter (shop-app = php-fpm, shop-web = Nginx + public/ assets).
# Nginx is a native sidecar (an init container with restartPolicy: Always):
# start-up: Nginx starts first, then php-fpm;
# shutdown: php-fpm (the app container) is stopped first; the kubelet sends
# Nginx its stop signal only after php-fpm has exited, so Nginx can
# still return the responses of requests php-fpm is finishing.
# Budget inside terminationGracePeriodSeconds 45:
# preStop sleep 10 s + php-fpm graceful stop <= 20 s (process_control_timeout)
# + Nginx graceful stop (a few seconds) < 45 s
apiVersion: v1
kind: ConfigMap
metadata:
name: shop-web-config
data:
# Same server block as the image chapter, but in a Pod the containers share
# one network namespace: php-fpm is 127.0.0.1:9000, not "app:9000".
default.conf: |
server {
listen 80;
server_name _;
root /var/www/html/public;
index index.php;
charset utf-8;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ ^/index\.php(/|$) {
fastcgi_pass 127.0.0.1:9000;
fastcgi_param SCRIPT_FILENAME /var/www/html/public/index.php;
include fastcgi_params;
fastcgi_hide_header X-Powered-By;
}
location ~ /\.(?!well-known).* {
deny all;
}
}
# Loaded after the image's zz-docker.conf. php.net: "Time limit for child
# processes to wait for a reaction on signals from master", default 0; give
# busy workers time to finish after SIGQUIT.
zz-kubernetes.conf: |
[global]
process_control_timeout = 20s
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: shop-web
labels:
app.kubernetes.io/name: shop-web
app.kubernetes.io/part-of: shop
spec:
replicas: 3
revisionHistoryLimit: 5
minReadySeconds: 10
selector:
matchLabels:
app.kubernetes.io/name: shop-web
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 25% # rounds up: 1 extra Pod for 3 replicas
maxUnavailable: 0
template:
metadata:
labels:
app.kubernetes.io/name: shop-web
app.kubernetes.io/part-of: shop
spec:
terminationGracePeriodSeconds: 45
initContainers:
- name: nginx # native sidecar: restartable init container
image: ghcr.io/acme/shop-web:1.8.0
restartPolicy: Always
ports:
- name: http
containerPort: 80
readinessProbe: # /up goes through Nginx AND php-fpm: tests both
httpGet:
path: /up
port: http
periodSeconds: 5
timeoutSeconds: 2
failureThreshold: 2
volumeMounts:
- name: config
mountPath: /etc/nginx/conf.d/default.conf
subPath: default.conf
containers:
- name: php-fpm
image: ghcr.io/acme/shop-app:1.8.0 # STOPSIGNAL SIGQUIT inherited from php:8.4-fpm
ports:
- name: fastcgi
containerPort: 9000
envFrom:
- secretRef:
name: shop-env # APP_KEY, DB_*, REDIS_* (config chapter)
startupProbe: # the entrypoint runs `php artisan optimize` first
tcpSocket:
port: fastcgi
periodSeconds: 2
failureThreshold: 30
livenessProbe: # the FPM master accepts connections
tcpSocket:
port: fastcgi
periodSeconds: 10
failureThreshold: 3
lifecycle:
preStop: # keep accepting while endpoints propagate
sleep:
seconds: 10
resources:
requests:
cpu: 250m
memory: 256Mi
limits:
memory: 512Mi
volumeMounts:
- name: config
mountPath: /usr/local/etc/php-fpm.d/zz-kubernetes.conf
subPath: zz-kubernetes.conf
volumes:
- name: config
configMap:
name: shop-web-config# Keep at least two shop-web Pods during voluntary disruptions. Workers and
# the scheduler get no PDB: losing one briefly is acceptable, and a PDB with
# replicas 1 and minAvailable 1 would block every node drain.
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: shop-web
spec:
minAvailable: 2
unhealthyPodEvictionPolicy: AlwaysAllow
selector:
matchLabels:
app.kubernetes.io/name: shop-web
---
apiVersion: v1
kind: Service
metadata:
name: shop-web
spec:
selector:
app.kubernetes.io/name: shop-web
ports:
- name: http
port: 80
targetPort: 80 # numeric: the named port lives on the Nginx sidecar (an init container)The queue worker Deployment: the same image with queue:work, a grace period longer than the job timeout, and --timeout below retry_after:
# shop-queue: `php artisan queue:work` as its own Deployment (same shop-app
# image, different command). No Service and no readiness probe: nothing sends
# it traffic; it pulls jobs from Redis.
# Timing chain (all three must hold):
# --timeout 90 < retry_after 120 (config/queue.php) (Laravel: several seconds shorter)
# --timeout 90 < terminationGracePeriodSeconds 110 (the current job can finish)
apiVersion: apps/v1
kind: Deployment
metadata:
name: shop-queue
labels:
app.kubernetes.io/name: shop-queue
app.kubernetes.io/part-of: shop
spec:
replicas: 2 # scale on queue length with KEDA or an external-metric HPA
revisionHistoryLimit: 5
selector:
matchLabels:
app.kubernetes.io/name: shop-queue
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1
maxUnavailable: 1
template:
metadata:
labels:
app.kubernetes.io/name: shop-queue
app.kubernetes.io/part-of: shop
spec:
terminationGracePeriodSeconds: 110
containers:
- name: worker
image: ghcr.io/acme/shop-app:1.8.0
# Exec form: php is PID 1 and receives the stop signal itself. The
# image's STOPSIGNAL is SIGQUIT; Laravel's worker finishes the current
# job on SIGQUIT, SIGTERM or SIGINT (needs the pcntl extension).
command: ["php", "artisan", "queue:work", "redis",
"--queue=default", "--sleep=3", "--tries=3",
"--timeout=90", "--max-time=3600"]
envFrom:
- secretRef:
name: shop-env
env:
- name: REDIS_QUEUE_RETRY_AFTER
value: "120"
resources:
requests:
cpu: 200m
memory: 256Mi
limits:
memory: 512MiThe scheduler, two options (choose one, see Choosing): a per-minute CronJob running schedule:run, or a single schedule:work Pod with Recreate:
# Option A for the Laravel scheduler: Kubernetes runs `schedule:run` every
# minute, exactly like the one cron line in the Laravel docs.
apiVersion: batch/v1
kind: CronJob
metadata:
name: shop-scheduler
labels:
app.kubernetes.io/name: shop-scheduler
app.kubernetes.io/part-of: shop
spec:
schedule: "* * * * *"
timeZone: "Etc/UTC"
concurrencyPolicy: Forbid # skip a minute rather than run two schedulers
startingDeadlineSeconds: 30 # >= 10: the controller checks every 10 s
successfulJobsHistoryLimit: 3
failedJobsHistoryLimit: 3
jobTemplate:
spec:
backoffLimit: 0 # a failed minute is not retried; the next minute runs
activeDeadlineSeconds: 120
ttlSecondsAfterFinished: 600
template:
metadata:
labels:
app.kubernetes.io/name: shop-scheduler
spec:
restartPolicy: Never
containers:
- name: schedule-run
image: ghcr.io/acme/shop-app:1.8.0
command: ["php", "artisan", "schedule:run"]
envFrom:
- secretRef:
name: shop-env
resources:
requests:
cpu: 100m
memory: 128Mi
limits:
memory: 256Mi# Option B for the Laravel scheduler: one long-running `schedule:work` Pod.
# Laravel documents schedule:work for local use (foreground, runs the scheduler
# every minute); in a cluster it needs two guards against double runs:
# - strategy Recreate: the old Pod is gone before the new one starts
# (a RollingUpdate with replicas 1 briefly runs two schedulers);
# - ->onOneServer() on tasks, with a shared cache (Redis), for the moments
# Recreate does not cover (a manually deleted Pod is replaced at once).
apiVersion: apps/v1
kind: Deployment
metadata:
name: shop-scheduler
labels:
app.kubernetes.io/name: shop-scheduler
app.kubernetes.io/part-of: shop
spec:
replicas: 1
selector:
matchLabels:
app.kubernetes.io/name: shop-scheduler
strategy:
type: Recreate
template:
metadata:
labels:
app.kubernetes.io/name: shop-scheduler
app.kubernetes.io/part-of: shop
spec:
terminationGracePeriodSeconds: 60
containers:
- name: schedule-work
image: ghcr.io/acme/shop-app:1.8.0
command: ["php", "artisan", "schedule:work"]
envFrom:
- secretRef:
name: shop-env
resources:
requests:
cpu: 100m
memory: 128Mi
limits:
memory: 256MiMigrations as a Job per release, failing fast on a broken migration and ignoring disruptions:
# shop-migrate: run once per release, before the new web/queue Pods roll out
# (a Helm pre-upgrade hook or an Argo CD PreSync hook in the packaging chapter).
apiVersion: batch/v1
kind: Job
metadata:
name: shop-migrate-1-8-0
labels:
app.kubernetes.io/name: shop-migrate
app.kubernetes.io/part-of: shop
spec:
backoffLimit: 2
activeDeadlineSeconds: 600 # wins over backoffLimit: no new Pods after 10 min
ttlSecondsAfterFinished: 3600 # delete Job and Pods one hour after it finishes
podFailurePolicy: # requires restartPolicy: Never
rules:
- action: FailJob # a migration that exits 1 is broken: do not retry it
onExitCodes:
containerName: migrate
operator: In
values: [1]
- action: Ignore # node drain or preemption: retry without counting
onPodConditions:
- type: DisruptionTarget
template:
metadata:
labels:
app.kubernetes.io/name: shop-migrate
spec:
restartPolicy: Never
containers:
- name: migrate
image: ghcr.io/acme/shop-app:1.8.0
command: ["php", "artisan", "migrate", "--force"]
envFrom:
- secretRef:
name: shop-envRedis for queues and cache as a single-member StatefulSet (exec and tcpSocket probes, a headless Service, a claim per Pod):
# shop-redis: a single Redis for Laravel queues and cache, as a StatefulSet so
# the Pod keeps its name (shop-redis-0), its DNS record and its volume.
# For replication and failover use an operator or a managed service
# (/database/replication-failover); replicas: 3 here would be three
# independent Redis servers, not a cluster.
apiVersion: v1
kind: Service
metadata:
name: shop-redis # headless: gives shop-redis-0.shop-redis.<ns>.svc
labels:
app.kubernetes.io/name: shop-redis
spec:
clusterIP: None
selector:
app.kubernetes.io/name: shop-redis
ports:
- name: redis
port: 6379
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: shop-redis
labels:
app.kubernetes.io/name: shop-redis
app.kubernetes.io/part-of: shop
spec:
serviceName: shop-redis # must name the headless Service above
replicas: 1
podManagementPolicy: OrderedReady # default; Parallel only relaxes scaling order
minReadySeconds: 10
revisionHistoryLimit: 5
updateStrategy:
type: RollingUpdate
rollingUpdate:
partition: 0 # raise to N to update only ordinals >= N (canary)
persistentVolumeClaimRetentionPolicy:
whenDeleted: Retain # deleting the StatefulSet keeps data-shop-redis-0
whenScaled: Retain
selector:
matchLabels:
app.kubernetes.io/name: shop-redis
template:
metadata:
labels:
app.kubernetes.io/name: shop-redis
app.kubernetes.io/part-of: shop
spec:
terminationGracePeriodSeconds: 30 # never 0 for a StatefulSet
containers:
- name: redis
image: redis:8.12-trixie
# Persistence flags as shown in the image docs: snapshot every 60 s
# if at least one write happened.
args: ["--save", "60", "1", "--loglevel", "warning"]
ports:
- name: redis
containerPort: 6379
readinessProbe: # exec probe: forks redis-cli in the container
exec:
command: ["redis-cli", "ping"]
periodSeconds: 10
timeoutSeconds: 2
livenessProbe: # tcpSocket probe: the port accepts connections
tcpSocket:
port: redis
initialDelaySeconds: 10
periodSeconds: 20
resources:
requests:
cpu: 100m
memory: 256Mi
limits:
memory: 512Mi
volumeMounts:
- name: data
mountPath: /data # the image's VOLUME /data
volumeClaimTemplates: # one PVC per Pod: data-shop-redis-0, -1, ...
- metadata:
name: data
spec:
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 10GiTwo more batch shapes and a node agent used in the concept blocks: an Indexed Job with per-index backoff and a pod failure policy, a nightly CronJob, and a DaemonSet with node selectors and tolerations:
# orders-export: one Pod per shard. Indexed completion mode gives every Pod a
# stable index 0..7 (env JOB_COMPLETION_INDEX, also in the hostname), and
# per-index backoff means one poisoned shard does not use up the whole budget.
apiVersion: batch/v1
kind: Job
metadata:
name: orders-export-2026-11-29
labels:
app.kubernetes.io/name: orders-export
spec:
completionMode: Indexed
completions: 8 # required for Indexed: the number of indexes
parallelism: 4 # at most 4 shards at a time
backoffLimitPerIndex: 2 # up to 2 retries per index; the 3rd failed Pod fails that index
maxFailedIndexes: 2 # more than 2 failed indexes fails the Job early
activeDeadlineSeconds: 3600
ttlSecondsAfterFinished: 86400
podFailurePolicy:
rules:
- action: FailIndex # exit 42 = bad input for this shard: do not retry it
onExitCodes:
containerName: export
operator: In
values: [42]
- action: Ignore # evicted or preempted: retry, do not count
onPodConditions:
- type: DisruptionTarget
template:
metadata:
labels:
app.kubernetes.io/name: orders-export
spec:
restartPolicy: Never # required by podFailurePolicy
containers:
- name: export
image: ghcr.io/acme/orders-export:1.4.2
# The program reads JOB_COMPLETION_INDEX itself and exports shard
# <index> of 8 to object storage; re-running a shard must be safe.
args: ["--shards=8", "--bucket=s3://acme-exports/2026-11-29"]
resources:
requests:
cpu: 500m
memory: 256Mi
limits:
memory: 512Mi# Nightly report. The schedule is interpreted in timeZone; concurrencyPolicy
# Forbid skips a run while yesterday's is still going; startingDeadlineSeconds
# lets a run start up to one hour late (controller down, Forbid skip).
apiVersion: batch/v1
kind: CronJob
metadata:
name: daily-sales-report
spec:
schedule: "30 2 * * *" # 02:30 every day
timeZone: "Etc/UTC"
concurrencyPolicy: Forbid
startingDeadlineSeconds: 3600
suspend: false
successfulJobsHistoryLimit: 3 # default 3
failedJobsHistoryLimit: 1 # default 1
jobTemplate:
spec:
backoffLimit: 2
activeDeadlineSeconds: 1800
template:
spec:
restartPolicy: OnFailure
containers:
- name: report
image: ghcr.io/acme/shop-app:1.8.0
command: ["php", "artisan", "reports:daily-sales"]
envFrom:
- secretRef:
name: shop-env# One log agent per Linux node, adapted from the DaemonSet example in the
# Kubernetes docs. nodeSelector and tolerations are a preview of the
# scheduling chapter: select the nodes, then tolerate their taints.
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: log-agent
namespace: kube-system
labels:
app.kubernetes.io/name: log-agent
spec:
selector:
matchLabels:
app.kubernetes.io/name: log-agent
updateStrategy:
type: RollingUpdate
rollingUpdate:
maxUnavailable: 1 # default 1: one node at a time without an agent
maxSurge: 0 # default 0; >0 runs old and new on a node briefly
template:
metadata:
labels:
app.kubernetes.io/name: log-agent
spec:
nodeSelector:
kubernetes.io/os: linux
tolerations:
# Also run on control-plane nodes (remove if they should not run Pods).
- key: node-role.kubernetes.io/control-plane
operator: Exists
effect: NoSchedule
terminationGracePeriodSeconds: 30
containers:
- name: fluentd
image: quay.io/fluentd_elasticsearch/fluentd:v5.0.1
resources:
requests:
cpu: 100m
memory: 200Mi
limits:
memory: 200Mi
volumeMounts:
- name: varlog
mountPath: /var/log
readOnly: true
volumes:
- name: varlog
hostPath:
path: /var/logThe offline checker used on all of these manifests (YAML parse, field names against the saved API reference, and the validation rules the API server would apply; no cluster involved):
#!/usr/bin/env ruby
# Offline checks for the chapter's manifests (no cluster, no kubectl):
# 1. every file parses as YAML;
# 2. every field name appears in the saved Kubernetes API reference pages
# (pipeline/sources/kubernetes-workloads/api-*.txt), free-form maps skipped;
# 3. the rules the API server would reject, checked by hand.
# Usage: ruby check-manifests.rb <api-reference-dir> <manifest files...>
require 'yaml'
api_dir, *files = ARGV
corpus = Dir[File.join(api_dir, 'api-*.txt')].map { |f| File.read(f) }.join("\n")
FREE = %w[labels annotations matchLabels nodeSelector data selector].freeze
$errors = []
def err(f, m); $errors << "#{f}: #{m}"; end
def keys(node, path, out)
case node
when Hash
node.each do |k, v|
out << [k, path]
next if FREE.include?(k) && !(k == 'selector' && v.is_a?(Hash) && (v.key?('matchLabels') || v.key?('matchExpressions')))
keys(v, path + [k], out)
end
when Array then node.each { |v| keys(v, path, out) }
end
end
def pod_spec(doc)
case doc['kind']
when 'Deployment', 'StatefulSet', 'DaemonSet', 'Job' then doc.dig('spec', 'template', 'spec')
when 'CronJob' then doc.dig('spec', 'jobTemplate', 'spec', 'template', 'spec')
end
end
def tmpl_labels(doc)
doc['kind'] == 'CronJob' ? doc.dig('spec', 'jobTemplate', 'spec', 'template', 'metadata', 'labels') : doc.dig('spec', 'template', 'metadata', 'labels')
end
count = 0
files.each do |f|
docs = YAML.load_stream(File.read(f)).compact
docs.each do |d|
count += 1
found = []; keys(d, [], found)
found.map(&:first).uniq.each { |k| err(f, "field '#{k}' not in saved API reference") unless corpus.include?(k) }
spec = d['spec'] || {}
ps = pod_spec(d)
if %w[Deployment StatefulSet DaemonSet].include?(d['kind'])
sel = spec.dig('selector', 'matchLabels') || {}
lab = tmpl_labels(d) || {}
err(f, "#{d['kind']} selector not a subset of template labels") unless sel.all? { |k, v| lab[k] == v }
rp = ps['restartPolicy']
err(f, "#{d['kind']} template restartPolicy must be Always") if rp && rp != 'Always'
end
if d['kind'] == 'Deployment'
ru = spec.dig('strategy', 'rollingUpdate') || {}
err(f, 'maxSurge and maxUnavailable both 0') if ru['maxSurge'].to_s == '0' && ru['maxUnavailable'].to_s == '0'
if spec['progressDeadlineSeconds'] && spec['minReadySeconds']
err(f, 'progressDeadlineSeconds must exceed minReadySeconds') unless spec['progressDeadlineSeconds'] > spec['minReadySeconds']
end
err(f, 'Recreate with rollingUpdate params') if spec.dig('strategy', 'type') == 'Recreate' && spec['strategy'].key?('rollingUpdate')
end
if %w[Job CronJob].include?(d['kind'])
js = d['kind'] == 'CronJob' ? spec.dig('jobTemplate', 'spec') : spec
err(f, 'Job restartPolicy must be OnFailure or Never') unless %w[OnFailure Never].include?(ps['restartPolicy'])
err(f, 'podFailurePolicy needs restartPolicy Never') if js['podFailurePolicy'] && ps['restartPolicy'] != 'Never'
err(f, 'Indexed Job needs completions') if js['completionMode'] == 'Indexed' && !js['completions']
err(f, 'backoffLimitPerIndex needs Indexed') if js['backoffLimitPerIndex'] && js['completionMode'] != 'Indexed'
acts = (js.dig('podFailurePolicy', 'rules') || []).map { |r| r['action'] }
err(f, 'FailIndex needs backoffLimitPerIndex') if acts.include?('FailIndex') && !js['backoffLimitPerIndex']
if d['kind'] == 'CronJob' && spec['startingDeadlineSeconds']
err(f, 'startingDeadlineSeconds < 10 may never schedule') if spec['startingDeadlineSeconds'] < 10
end
end
if d['kind'] == 'StatefulSet'
svc = files.flat_map { |g| YAML.load_stream(File.read(g)).compact }.find { |x| x['kind'] == 'Service' && x.dig('metadata', 'name') == spec['serviceName'] }
err(f, 'serviceName has no headless Service') unless svc && svc.dig('spec', 'clusterIP') == 'None'
err(f, 'terminationGracePeriodSeconds 0 in a StatefulSet') if ps['terminationGracePeriodSeconds'] == 0
end
if d['kind'] == 'PodDisruptionBudget'
err(f, 'PDB sets both minAvailable and maxUnavailable') if spec.key?('minAvailable') && spec.key?('maxUnavailable')
end
if ps
grace = ps['terminationGracePeriodSeconds'] || 30
((ps['containers'] || []) + (ps['initContainers'] || [])).each do |c|
%w[livenessProbe startupProbe].each do |p|
st = c.dig(p, 'successThreshold')
err(f, "#{c['name']} #{p} successThreshold must be 1") if st && st != 1
end
%w[livenessProbe readinessProbe startupProbe].each do |p|
gp = c.dig(p, 'grpc', 'port')
err(f, "#{c['name']} grpc probe port must be numeric") if gp && !gp.is_a?(Integer)
m = (c[p] || {}).keys & %w[exec httpGet tcpSocket grpc]
err(f, "#{c['name']} #{p} needs exactly one mechanism") if c[p] && m.size != 1
end
if c['restartPolicy'] && !(ps['initContainers'] || []).include?(c)
err(f, "#{c['name']} container-level restartPolicy outside initContainers")
end
sl = c.dig('lifecycle', 'preStop', 'sleep', 'seconds')
err(f, "#{c['name']} preStop sleep #{sl}s >= grace #{grace}s") if sl && sl >= grace
end
end
end
end
puts "#{files.size} files, #{count} objects"
if $errors.empty? then puts 'manifests ok' else puts $errors; exit 1 endThe Laravel angle
- Health route. Laravel's
/up"will return a 200 HTTP response if the application has booted without exceptions. Otherwise, a 500 HTTP response will be returned", and the deployment docs name "orchestration system such as Kubernetes" as a consumer. Probing it through Nginx tests Nginx, FastCGI and the framework boot in one request; add checks (database, cache) with a listener on theDiagnosingHealthevent only if the Pod truly cannot serve without them, since/upis the readiness probe here. - Workers stop gracefully on the image's signal. "When a queue worker receives a termination signal such as
SIGQUIT,SIGTERM, orSIGINTwhile processing a job, the worker will finish its current job before exiting." Theshop-appimage inheritsSTOPSIGNAL SIGQUIT, which the worker accepts; job timeouts need the PCNTL extension. Long jobs can react to the signal throughIlluminate\Contracts\Queue\Interruptible:
<?php
// app/Jobs/ImportProducts.php (shape from the Laravel 13 queue docs): stop early on SIGTERM/SIGQUIT
namespace App\Jobs;
use App\Models\Import;
use Illuminate\Contracts\Queue\Interruptible;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
class ImportProducts implements ShouldQueue, Interruptible
{
use Queueable;
protected bool $shouldStop = false;
public function __construct(public Import $import) {}
public function handle(): void
{
foreach ($this->import->pendingRows() as $row) {
if ($this->shouldStop) {
break; // the Pod is terminating: save progress, let the next worker resume
}
// import the product row ...
}
$this->import->saveProgress();
}
public function interrupted(int $signal): void
{
$this->shouldStop = true;
}
}- Three numbers that must agree.
--timeout(default 60 s) "should always be at least several seconds shorter than yourretry_afterconfiguration value", or "your jobs may be processed twice";terminationGracePeriodSecondsmust exceed--timeoutso the current job can finish, which is Kubernetes' version of Supervisor'sstopwaitsecs("greater than the number of seconds consumed by your longest running job"). - Exits on purpose.
--max-time=3600and--memorymake the worker exit so the container restarts with fresh memory ("queue workers are long-lived processes and store the booted application state in memory"); underrestartPolicy: Alwayseach exit is a restart, and because the worker ran more than 10 minutes the kubelet's backoff is reset, so the restart is immediate.--max-jobswith a small number or--stop-when-emptyin a Deployment produces fast, repeated exits andCrashLoopBackOff; use--stop-when-emptyonly in a Job. queue:restartis not needed on deploy. It exists because VM workers "will not notice changes in your code base"; in Kubernetes a new image means new Pods, and the old worker Pods receive the stop signal and finish their current job.- The scheduler must run once. "only a single cron entry is needed on your server" becomes a CronJob (
schedule:runevery minute,Forbid), or oneschedule:workPod. Laravel presentsschedule:workfor running the scheduler locally ("This command will run in the foreground and invoke the scheduler every minute"); in a cluster it works as a single-replicaRecreateDeployment. For defence in depth addonOneServer()("The first server to obtain the task will secure an atomic lock") with a shared Redis cache, andwithoutOverlapping()for long tasks. - Migrations once per release. A Job (or a Helm/Argo CD hook Job), never the web entrypoint or an init container, so three replicas do not race;
podFailurePolicyfails a broken migration immediately instead of retrying it six times. - Config at start, not at build. The entrypoint's
php artisan optimizeruns in every Pod start with the real environment from theshop-envSecret; a startup probe on FPM allows for it. ConfigMaps and Secrets are in Config, Secrets & Storage. - Octane / FrankenPHP. One process per Pod: an
httpGetprobe on/up,--max-requestsfor memory hygiene, and the same preStop + graceful-stop budget; no sidecar ordering to think about.
Solving the classic problems
| Problem | Solution | How | Advantage | Cost / limit |
|---|---|---|---|---|
| 502s / resets on every rollout | Delay, then drain | preStop sleep 5–10 s, then Shutdown / FPM SIGQUIT | Zero dropped requests | Slower rollouts; budget to keep |
| Slow boot killed by liveness | Startup probe | Same endpoint, failureThreshold × periodSeconds ≥ worst boot | Fast liveness after start | One more probe to tune |
| Database blip restarts the fleet | Local liveness | Dependencies only in readiness | Outage = fewer endpoints, not restarts | All Pods unready if the dependency is shared |
| Traffic before the app is ready | Readiness + minReadySeconds | /readyz, 5–10 s minReadySeconds | Rollout waits for real readiness | Rollouts take longer |
| Bad release keeps rolling | Gate on progress | progressDeadlineSeconds, kubectl rollout status in CI, rollout undo | Stops at the old ReplicaSet's floor | Does not stop a release that is ready but wrong (canary for that) |
| Long jobs killed on deploy | Grace period > longest job | terminationGracePeriodSeconds > --timeout, Interruptible jobs | Jobs finish or checkpoint | Slow Pod turnover |
| Scheduled tasks run three times | One scheduler | CronJob Forbid or schedule:work + Recreate + onOneServer | Each task once per tick | Shared cache needed for locks |
| Migrations race on scale-up | Migration Job per release | Job + hook (Helm, Argo CD) | Once, before new Pods | Backward-compatible migrations required |
| Drain blocked or too aggressive | PDB sized to replicas | maxUnavailable: 1, AlwaysAllow | Safe, finishing drains | A budget per workload |
| Same tag, different code | Digests | name:tag@sha256:... from CI | Identical Pods, exact rollback | Tooling writes digests |
| Batch retries waste time | Pod failure policy | FailJob/FailIndex on known codes, Ignore disruptions | Fast failure, no false retries | Exit codes become an API |
| Finished Jobs pile up | TTL and history limits | ttlSecondsAfterFinished, CronJob history limits | Clean namespace | Logs vanish with the Pod: ship them first |
502s or connection resets on every rollout
The deletion starts endpoint removal and the stop sequence at the same time. Keep accepting for the time the slowest consumer needs (kube-proxy is fast; cloud load balancers and some Ingress setups take seconds): preStop.sleep 5–10 s, or DRAIN_DELAY in the Go app. Then stop accepting and finish in-flight work within the rest of the grace period. Check with a load generator during kubectl rollout restart: zero non-2xx responses is the target.
A slow start that restarts forever
kubectl describe pod shows "Liveness probe failed" during the first minute and RESTARTS climbing. Add a startup probe on the liveness endpoint with periodSeconds: 2-10 and a failureThreshold that covers the slowest observed start on a busy node, and remove initialDelaySeconds from liveness.
Long jobs killed on deploy
Raise terminationGracePeriodSeconds above the longest job (--timeout), keep retry_after above --timeout, and make very long jobs Interruptible so they checkpoint and let the next worker continue. Jobs that run for hours belong in a Kubernetes Job, not a queue worker.
Scheduled tasks running more than once
Never run schedule:work or a cron daemon inside the web or worker Pods. Run exactly one scheduler (CronJob with Forbid, or a single-replica Recreate Deployment) and use onOneServer() on tasks that must never double, since a CronJob is "approximately once".
A rollout that is stuck
kubectl rollout status waits, kubectl get rs shows the new ReplicaSet with fewer ready Pods than desired, describe on a new Pod shows the reason (image pull, probe, scheduling). Fix forward with a new image or kubectl rollout undo; in GitOps revert the commit. For a StatefulSet stuck on a broken Pod, revert the template and delete the broken Pod.
Node drains that hang
kubectl drain repeating "Cannot evict pod as it would violate the pod's disruption budget": a PDB that allows zero disruptions (one replica, or minAvailable = replicas), or Pods that never become healthy. Allow at least one disruption, add replicas, and set unhealthyPodEvictionPolicy: AlwaysAllow.
Choosing
Which controller
| The process | Controller | Why |
|---|---|---|
| Stateless HTTP/gRPC service (Go API, Laravel web) | Deployment | Interchangeable replicas, rolling updates |
Queue consumer (queue:work, Go consumer) | Deployment (+ KEDA/HPA on queue length) | Continuous, interchangeable |
| Database, broker, consensus member | StatefulSet via an operator, or a managed service | Identity, per-member storage, ordered changes |
| Single Redis/cache for a small app | StatefulSet, replicas 1 | Keeps its volume and name |
| Agent on every node | DaemonSet | One per node, node files and sockets |
| Migration, backfill, export | Job (Indexed for shards) | Runs to completion with retries |
| Periodic task | CronJob | Schedule, concurrency, deadlines |
| Laravel scheduler | CronJob schedule:run or one schedule:work Pod | Exactly one scheduler |
Which probe for which check
| Check | Probe | Mechanism |
|---|---|---|
| "Process can make progress" | Liveness | httpGet on a constant endpoint; tcpSocket for FPM, Redis |
| "Finished booting" | Startup | Same endpoint as liveness, generous threshold |
| "Can serve users now" (dependencies, warm cache, not draining) | Readiness | httpGet /readyz or Laravel /up |
| Process that crashes on its own when broken | None for liveness | restartPolicy handles it |
| gRPC service | All three | grpc with service names |
| Worker without a port | Usually none; or exec on a heartbeat file | Exit on failure instead |
Which update strategy
| Situation | Strategy |
|---|---|
| Stateless, spare capacity | RollingUpdate maxSurge 25%, maxUnavailable 0 |
| Stateless, no spare capacity | RollingUpdate maxSurge 0, maxUnavailable 1 |
| Two versions must never overlap | Recreate (Deployment), accept downtime |
| Stateful members, cautious | StatefulSet RollingUpdate + partition canary |
| Manual control per member | StatefulSet / DaemonSet OnDelete |
| Traffic-percentage canary, automated analysis | Argo Rollouts / Flagger (Deployment Strategies) |
Which Laravel scheduler model
| Model | For | Against |
|---|---|---|
CronJob * * * * * running schedule:run, Forbid | Mirrors the documented cron line; no long-running Pod; failures visible per minute | 1,440 Jobs a day to clean up; Pod start latency each minute; sub-minute tasks keep each Job running the whole minute |
Deployment, replicas 1, Recreate, schedule:work | One warm process, no per-minute Pod churn, sub-minute tasks natural | schedule:work is documented for local use; a gap during each rollout; needs onOneServer for safety |
| Scheduler inside every web/worker Pod | Nothing | Every task runs once per Pod |
In architecture: from a single process to a distributed system
Workload objects are where application design meets the platform: the number of controllers mirrors the number of independently scaled processes, and every one of them needs probes, a termination budget and an update strategy that match what the process does.
Monolith: one app, four controllers
A Laravel monolith on a small cluster is still four workloads, not one: the web Deployment (Nginx sidecar + php-fpm), the queue worker Deployment, the scheduler (CronJob or a single schedule:work Pod) and a migration Job per release, all from one image, plus Redis as a StatefulSet or a managed service. The essentials are already the whole of this page: /up readiness, preStop and process_control_timeout, a worker grace period above the job timeout, exactly one scheduler, and a digest per release so all four run the same code.
Modular monolith: more workers, same image
The codebase grows queues with different profiles (fast emails, slow PDF rendering, imports). Each gets its own worker Deployment (--queue=pdf, its own --timeout, grace period and resources), so a backlog of imports no longer delays password-reset emails and each pool scales on its own queue length. Versioning stays unified: one image digest, applied to every Deployment in one Helm release or Kustomize overlay.
Microservices: many Deployments, one golden path
Twenty Go and PHP services owned by different teams, built by GitHub Actions or GitLab CI, packaged with Helm or Kustomize and synced by Argo CD. What the platform team standardises is the workload contract: every service exposes /livez, /readyz (and /startupz if slow), honours SIGTERM within a stated budget, ships a PDB and a spread constraint, and is deployed by digest. A typical release of orders-api 1.5.0:
1 CI (GitHub Actions): test, build, push image -> digest D; open a PR in the GitOps repo: image orders-api@D
2 Argo CD syncs: PreSync hook Job (migrations) -> Deployment template changes -> new ReplicaSet
3 RollingUpdate maxSurge 1 / maxUnavailable 0: each new Pod passes startup, then readiness, then minReadySeconds
4 each old Pod: endpoint removed, preStop 5 s, SIGTERM, drain <= 20 s, exit; PDB not involved
5 kubectl rollout status (or Argo CD health) reports Healthy; on ProgressDeadlineExceeded the sync fails and the Git revert rolls backThe cluster, node pools and managed databases around it are typically provisioned with Terraform; packaging and GitOps are in Packaging for Kubernetes; the architectural trade-offs of running Kubernetes at all are in Containers & Kubernetes.
Distributed data: stateful workloads, queues and caches
State changes every rule above. A StatefulSet member cannot be "just replaced" while it holds the only copy of data, so production databases are run by operators or bought as managed services, and the application Deployments treat them as external dependencies (readiness depends on them, liveness never does). Queues decouple the web tier from the workers: the web Deployment scales on request rate, the worker Deployment on queue depth (KEDA on Redis lists or SQS, or an HPA on an external metric), and the delivery guarantees ("at least once", idempotent handlers, retry_after) live in the application, as Competing Consumers & Scaling describes. Caches in Redis survive Pod replacement only because the Redis Pod keeps its claim; a cache inside the app Pod (APCu, an in-process Go map) is lost on every rollout and must be warmed (a startup probe pays for that). Replication and failover of the data itself are in Replication & Failover.
Scaling path: 1x, 10x, 100x
| Scale | Workloads | Rollouts | Operations |
|---|---|---|---|
| 1x (one team, one cluster) | Hand-written manifests: web, worker, scheduler, migration Job, Redis StatefulSet | kubectl apply, rollout status in CI, rollout undo | Probes and budgets reviewed by hand |
| 10x (several teams) | Helm charts or Kustomize bases encoding the contract; PDBs, spread, HPAs/KEDA everywhere | GitOps (Argo CD, Flux), digests written by CI, hook Jobs for migrations | Policies (Kyverno, Gatekeeper) reject manifests without probes, requests or digests |
| 100x (many clusters, regions) | Operators for stateful systems, managed databases, per-region worker pools | Progressive delivery (Argo Rollouts, Flagger) with automated analysis, cluster-by-cluster waves | Fleet-level SLOs on rollout errors, drain automation respecting PDBs, Terraform for clusters and node pools |
Lab
Label: every kubectl command below is expected, not run: no Kubernetes cluster may be started in this build environment (AUTHORING cost rule), and kubectl was deliberately not invoked even client-side, because it would contact whatever cluster a kubeconfig points at. Expected output is either quoted from the Kubernetes documentation's own samples (marked "docs sample") or written as a shape with placeholders, never as invented names, timings or counts. Steps marked ran on the host were executed on macOS (Go 1.27.4, darwin/arm64) and show real output, saved in pipeline/sources/kubernetes-workloads/lab-host-output.txt.
1. Test the Go service (ran on the host)
cd docs/snippets/platform/kubernetes-workloads/go-service
gofmt -l . ; go vet ./... ; go test -race -count=1 -v ./... 2>&1 | grep -E "^(--- |ok|FAIL)"
# --- PASS: TestProbesDuringStartup (0.00s)
# --- PASS: TestDependencyFailsReadinessOnly (0.00s)
# --- PASS: TestServeDrainsOnSIGTERM (0.62s)
# --- PASS: TestServeShutdownTimeout (0.25s)
# --- PASS: TestEnvDuration (0.00s)
# ok academy/kubernetes-workloads 2.203s2. Probe endpoints and the SIGTERM sequence on a real process (ran on the host)
go build -o orders-api .
PORT=18081 WARMUP=2s DRAIN_DELAY=2s SHUTDOWN_TIMEOUT=5s ./orders-api & PID=$!
sleep 0.5
curl -s -o /dev/null -w '%{http_code}\n' localhost:18081/livez # t=0.5s -> 200
curl -s -o /dev/null -w '%{http_code}\n' localhost:18081/startupz # t=0.5s -> 503
curl -s -o /dev/null -w '%{http_code}\n' localhost:18081/readyz # t=0.5s -> 503
sleep 2
curl -s localhost:18081/startupz ; curl -s localhost:18081/readyz # t=2.5s -> started / ready
kill -TERM $PID # what the kubelet asks the runtime to send
sleep 0.5
curl -s -w ' %{http_code}\n' localhost:18081/readyz # 0.5 s into DRAIN_DELAY -> draining 503
curl -s localhost:18081/orders/43 # still served -> {"id":"43","status":"paid"}
wait $PID ; echo $? # -> 0
# server log (time field removed):
# {"level":"INFO","msg":"listening","addr":"[::]:18081"}
# {"level":"INFO","msg":"started"}
# {"level":"INFO","msg":"draining","delay":"2s"}
# {"level":"INFO","msg":"stopped"}The same shape is what a Pod shows: the startup probe fails until warm-up, readiness follows, and after the stop signal the process keeps answering business requests during the delay, reports not-ready, drains and exits 0 well before a 30 s SIGKILL.
3. Cross-compile for the cluster and check the manifests offline (ran on the host)
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags "-s -w" -o orders-api-linux-amd64 .
file orders-api-linux-amd64
# orders-api-linux-amd64: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, Go BuildID=..., stripped
cd .. && ruby manifests/check-manifests.rb ../../../../pipeline/sources/kubernetes-workloads $(find manifests -name '*.yaml' | sort)
# 14 files, 17 objects
# manifests okThe checker parses every file, looks up every field name in the saved API reference pages and applies the rules the API server would enforce (selector subset of template labels, restartPolicy per controller, maxSurge/maxUnavailable not both 0, progressDeadlineSeconds greater than minReadySeconds, podFailurePolicy with Never, completions for Indexed Jobs, one probe mechanism, successThreshold 1 on liveness/startup, numeric gRPC ports, a headless Service behind each StatefulSet, preStop shorter than the grace period). It is not a schema validation; a cluster's --dry-run=server is.
4. Apply and watch a rollout (expected, not run)
kubectl apply -f manifests/go-service/deployment.yaml -f manifests/go-service/service.yaml -f manifests/go-service/pdb.yaml
# hpa.yaml is opt-in: apply it only after removing replicas from deployment.yaml (see the HPA preview)
kubectl rollout status deployment/orders-api --timeout=10m
# docs sample: Waiting for rollout to finish: 2 out of 3 new replicas have been updated...
# docs sample: deployment "nginx-deployment" successfully rolled out (name differs here)
kubectl get rs -l app.kubernetes.io/name=orders-api
# shape: orders-api-<hash> DESIRED 3 CURRENT 3 READY 3
kubectl set image deployment/orders-api api=ghcr.io/acme/orders-api:1.5.0
kubectl get pods -l app.kubernetes.io/name=orders-api -w
# shape: one new Pod Pending -> Running 0/1 -> 1/1, then one old Pod Terminating; repeated 3 times (maxSurge 1, maxUnavailable 0)
kubectl rollout history deployment/orders-api
# docs sample shape: REVISION CHANGE-CAUSE / 1 <none> / 2 <none>
kubectl rollout undo deployment/orders-api5. A broken release stops at the deadline (expected, not run)
kubectl set image deployment/orders-api api=ghcr.io/acme/orders-api:does-not-exist
kubectl rollout status deployment/orders-api
# docs sample: Waiting for rollout to finish: 2 out of 3 new replicas have been updated...
# docs sample: error: deployment "nginx" exceeded its progress deadline
echo $?
# docs sample: 1
kubectl describe deployment orders-api | grep -A3 Conditions
# shape: Progressing False ProgressDeadlineExceeded (after progressDeadlineSeconds = 300 s here)
kubectl get pods -l app.kubernetes.io/name=orders-api
# shape: 3 old Pods Running 1/1 (maxUnavailable 0 kept them), 1 new Pod ImagePullBackOff6. Liveness, CrashLoopBackOff and the previous container's logs (expected, not run)
kubectl describe pod <orders-api-pod>
# docs sample (probe task page):
# Warning Unhealthy 10s (x3 over 20s) kubelet, node01 Liveness probe failed: cat: can't open '/tmp/healthy': No such file or directory
# Normal Killing 10s kubelet, node01 Container liveness failed liveness probe, will be restarted
kubectl get pods
# docs sample shape: NAME ... READY 0/1 STATUS CrashLoopBackOff RESTARTS <n>
kubectl logs <pod> --previous # the crashed container's output
kubectl debug -it <pod> --image=busybox:1.28 --target=api
# docs sample: Defaulting debug container name to debugger-8xzrl.
# If you don't see a command prompt, try pressing enter.7. Zero-error rollout under load (expected, not run)
# in one terminal: constant load through the Service (any HTTP load tool)
kubectl run load --rm -it --image=busybox:1.28 -- sh -c \
'while true; do wget -q -O /dev/null -T 2 http://orders-api/orders/1 || echo FAIL; done'
# in another: replace every Pod
kubectl rollout restart deployment/orders-api && kubectl rollout status deployment/orders-api
# expected with preStop 5 s + Shutdown: no FAIL lines
# expected after removing the preStop hook and setting DRAIN_DELAY=0s: occasional FAIL lines during the restart8. Jobs, CronJobs and a drain (expected, not run)
kubectl apply -f manifests/batch/indexed-job.yaml
kubectl get pods -l batch.kubernetes.io/job-name=orders-export-2026-11-29 -L batch.kubernetes.io/job-completion-index
# shape: 4 Pods at a time, completion-index column 0..7
kubectl get job orders-export-2026-11-29 -o jsonpath='{.status.failedIndexes}'
kubectl create job --from=cronjob/shop-scheduler shop-scheduler-manual-1
kubectl get cronjob shop-scheduler # SCHEDULE * * * * *, LAST SCHEDULE <age>, ACTIVE 0 or 1 (Forbid)
kubectl drain node-3 --ignore-daemonsets
# shape: evicting pod default/shop-web-...; with minAvailable 2 the second shop-web eviction is retried until a replacement is ReadyCommon misconceptions
| Belief | Reality |
|---|---|
CrashLoopBackOff is a Pod phase | A kubectl display status; the phase is usually Running |
| Liveness should check dependencies | Dependencies belong in readiness; liveness failures restart containers and can cascade |
| Without a readiness probe the Pod gets no traffic | Without one, readiness counts as success as soon as the container runs |
| SIGTERM comes after the Pod leaves the load balancer | Endpoint removal and the stop sequence start together |
| The grace period starts after preStop | It starts at deletion and includes the preStop hook |
maxUnavailable: 0 guarantees zero downtime | It guarantees counts; probes and draining guarantee correctness |
| A PDB protects rolling updates | Rolling updates ignore PDBs; they limit voluntary evictions |
rollout undo reverts the whole manifest | It restores the previous Pod template only |
| A StatefulSet makes a database highly available | It provides identity and storage; replication and failover are separate |
| Deleting a StatefulSet deletes its data | PVCs are retained unless the retention policy says Delete |
| A CronJob runs exactly once per tick | "Approximately once"; Jobs must be idempotent |
| A sidecar is any second container | Only an init container with restartPolicy: Always gets sidecar start/stop ordering |
| Exit 0 is never restarted | Under restartPolicy: Always it is restarted, with backoff if it repeats |
imagePullPolicy: Always re-downloads the image | It resolves the digest and pulls only missing layers |
| The selector can be edited later | It is immutable for Deployments, StatefulSets, DaemonSets, ReplicaSets and Jobs |
Cheat sheet
| Topic | Remember |
|---|---|
| Controller choice | Stateless → Deployment; identity/storage → StatefulSet (operator for real databases); per node → DaemonSet; finite → Job; periodic → CronJob |
| Pod | Shared network namespace (localhost), shared volumes, one lifecycle; never create bare Pods |
| Init / sidecar | Init: sequential, must exit 0, idempotent; sidecar: initContainers + restartPolicy: Always, starts first, stops last |
| Phases | Pending, Running, Succeeded, Failed, Unknown; STATUS column is not the phase |
| Restarts | Always / OnFailure / Never; backoff 10 s doubling to 300 s, reset after 10 min |
| Probes | Startup gates the others; liveness local and loose; readiness includes dependencies |
| Probe defaults | delay 0, period 10, timeout 1, failure 3, success 1 (must be 1 for liveness/startup) |
| Termination | Deletion → endpoints not ready AND preStop → stop signal → drain → SIGKILL at grace (30 s) |
| Budget | preStop + drain < terminationGracePeriodSeconds; grace > longest request or job |
| Rollout | 25%/25% defaults (surge up, unavailable down); minReadySeconds; progressDeadlineSeconds 600; history 10 |
| kubectl rollout | status (exit 1 past deadline), history, undo --to-revision, pause/resume (Deployments only), restart |
| StatefulSet | Headless Service, name-N DNS, PVC per ordinal, ordered 0→N-1 and back, partition, never grace 0 |
| Job | completions, parallelism, backoffLimit 6, activeDeadlineSeconds wins, TTL, Indexed + per-index backoff, podFailurePolicy needs Never |
| CronJob | timeZone, Forbid, startingDeadlineSeconds ≥ 10, history 3/1, idempotent jobs |
| PDB | One of minAvailable/maxUnavailable, evictions only, AlwaysAllow, never zero disruptions |
| Images | Deploy tag@sha256:digest; omitted pull policy derived once at creation |
| Laravel | Nginx sidecar + FPM (127.0.0.1:9000, process_control_timeout), workers with grace > --timeout < retry_after, one scheduler, migration Job |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Your Go service returns a burst of 502s from the Ingress on every rollout, although it handles SIGTERM with http.Server.Shutdown. Explain the cause and the fix. Must-know
Answer
Answer: Deleting a Pod starts two things in parallel: the endpoint is marked not ready (and the Ingress controller, kube-proxy and any cloud load balancer remove it a little later), and the kubelet starts the stop sequence. If the app receives SIGTERM immediately and Shutdown closes the listener, connections the traffic layer still sends are refused. Fix: wait before closing the listener, either with lifecycle.preStop.sleep.seconds: 5 (no shell needed) or an in-app delay, then Shutdown with a timeout; keep preStop + drain below terminationGracePeriodSeconds, because the grace period includes the preStop hook.
2 — Why must a liveness probe not check the database, and where does that check go instead? Must-know
Answer
Answer: A failed liveness probe kills and restarts the container. When the shared database is down, every replica fails at once and all of them restart, which does not fix the database and adds a restart storm when it returns; the docs warn that incorrect liveness probes "can lead to cascading failures". The dependency check goes into readiness: an unready Pod is only removed from Service endpoints and keeps running, and comes back automatically when the check passes. Liveness should test only that the process can still make progress.
3 — A JVM or Laravel app takes up to 90 s to start on a busy node and keeps restarting during start. Which probe settings fix it without slowing failure detection later? Must-know
Answer
Answer: Add a startup probe on the same endpoint as liveness with periodSeconds × failureThreshold above the worst start time (for example periodSeconds: 5, failureThreshold: 24 = 120 s). Liveness and readiness do not run until the startup probe succeeds, so liveness can keep a short periodSeconds: 10, failureThreshold: 3 (30 s) for the rest of the container's life. A large initialDelaySeconds on liveness instead would delay detection on every start and still fail a slower start.
4 — With 10 replicas and the default rolling-update parameters, how many Pods can exist and how many must be available during a rollout? What changes with maxSurge: 0? Must-know
Answer
Answer: Defaults are 25% each. maxSurge rounds up: 2.5 → 3, so at most 13 counted Pods (Pods still terminating are not counted, so the real total and resource use can be higher until their grace periods end); maxUnavailable rounds down: 2.5 → 2, so at least 8 available. With maxSurge: 0 no extra Pods are created; the controller first scales the old ReplicaSet down (by up to maxUnavailable) and then creates new Pods in the freed slots, so capacity drops during the rollout but no spare cluster capacity is needed. Both cannot be 0 at once.
5 — Why can you not change spec.selector.matchLabels of a Deployment, and how should labels be designed so you never need to? Must-know
Answer
Answer: In apps/v1 the selector is immutable after creation; changing it would make the Deployment disown its ReplicaSets and Pods. The only way is to delete and recreate the Deployment (possibly with --cascade=orphan). Put only stable identity labels in the selector (app.kubernetes.io/name, plus instance if needed) and put changing labels such as version only in the Pod template. Also avoid selectors that overlap with another controller's Pods.
6 — A Laravel queue worker Deployment loses jobs mid-way on every deploy. Which three settings must agree, and how? Important
Answer
Answer: The worker finishes the current job on SIGQUIT/SIGTERM/SIGINT, but it must be given the time: terminationGracePeriodSeconds must be greater than the worker's --timeout, otherwise SIGKILL interrupts the job. --timeout must be several seconds shorter than the connection's retry_after, otherwise a job still running is released and processed twice. And the worker must be PID 1 (exec-form command) with PCNTL available. Long jobs can also implement Interruptible to checkpoint when the signal arrives.
7 — When should Nginx be a native sidecar of php-fpm, and what goes wrong with two regular containers? Important
Answer
Answer: When both run in one Pod on Kubernetes v1.29+ (stable v1.33): Nginx in initContainers with restartPolicy: Always starts before php-fpm and receives its stop signal only after php-fpm has exited, so it can still return the responses FPM is finishing. With two regular containers, start order is undefined and both get the stop signal "at different times and in an arbitrary order", so Nginx may stop first (dropped responses) or FPM may stop first (502s). In both layouts fastcgi_pass is 127.0.0.1:9000 and FPM should get a process_control_timeout so busy workers have time to finish after SIGQUIT.
8 — A Job should fail immediately when its container exits with code 42, ignore Pods lost to node drains, and retry other failures. Write the relevant fields. Important
Answer
Answer: restartPolicy: Never in the Pod template (required), backoffLimit for ordinary retries, and a podFailurePolicy with two rules: first action: FailJob with onExitCodes {containerName: main, operator: In, values: [42]}, then action: Ignore with onPodConditions of type: DisruptionTarget. Rules are evaluated in order and the first match wins; unmatched failures use the default handling (count toward backoffLimit). For an Indexed Job, FailIndex with backoffLimitPerIndex fails only that index.
9 — How do you roll a new version out to one member of a 3-replica StatefulSet first, and what must you do if that member never becomes Ready? Important
Answer
Answer: Set updateStrategy.rollingUpdate.partition: 2, then change the template: only ordinals ≥ 2 (name-2) are updated. Lower the partition to 1 and 0 to continue. If the new name-2 never becomes Running and Ready under OrderedReady, reverting the template is not enough: the StatefulSet keeps waiting for the broken Pod. Revert the template and delete the broken Pod so it is recreated from the good revision (the documented forced rollback).
10 — A node drain hangs for an hour on "Cannot evict pod as it would violate the pod's disruption budget". Give two causes and fixes. Important
Answer
Answer: (1) The PDB allows zero disruptions: one replica with minAvailable: 1, or minAvailable equal to replicas, or maxUnavailable: 0; fix by allowing one disruption and running enough replicas spread over nodes. (2) Pods are unhealthy (crash-looping, never Ready), so the budget is already used up; with the default IfHealthyBudget they cannot be evicted, while unhealthyPodEvictionPolicy: AlwaysAllow lets the drain remove them. A PDB never affects rolling updates or direct deletes.
11 — Two options for the Laravel scheduler in Kubernetes: compare them and name the setting that prevents double runs in each. Good to know
Answer
Answer: A CronJob with schedule: "* * * * *" running php artisan schedule:run mirrors Laravel's single cron entry; concurrencyPolicy: Forbid prevents two scheduler runs overlapping, and history limits plus ttlSecondsAfterFinished clean up the many Jobs. A one-replica Deployment running schedule:work (documented by Laravel for local use) avoids per-minute Pods; strategy: Recreate prevents old and new schedulers running together during a rollout. In both, ->onOneServer() with a shared cache adds a lock, because a CronJob is only "approximately once".
12 — Your manifest uses image: orders-api:1.4 and the tag was re-pushed. Why do Pods now run two versions, and what reference should CI write instead? Good to know
Answer
Answer: A non-latest tag defaults to imagePullPolicy: IfNotPresent: nodes that cached the old 1.4 keep running it, nodes without it pull the new bytes, so "you might end up with a mix of Pods running the old and new code". CI should write orders-api:1.4.2@sha256:<digest>; with a digest, "Only the digest will be used for pulling" and every node runs the same image, and a rollback to that revision is exact.
Glossary
| Term | Meaning |
|---|---|
| Pod | Smallest deployable unit: one or more containers with a shared network namespace, optional shared volumes, one lifecycle |
| Container (app container) | An entry in spec.containers: the main processes of the Pod |
| Init container | Runs before app containers, sequentially, must exit 0; idempotent |
| Sidecar container / restartable init container | Init container with restartPolicy: Always: starts first, runs for the Pod's life, stops after app containers (stable v1.33) |
| Ephemeral container | Temporary debug container added via the ephemeralcontainers subresource; no ports, probes or restarts |
| kubectl debug | Adds an ephemeral container (--target), copies a Pod (--copy-to) or debugs a node |
| Pod phases | status.phase: Pending Running Succeeded Failed Unknown |
| Container states | Waiting, Running, Terminated (with reason and exit code) |
| Pod conditions | PodScheduled, PodReadyToStartContainers, Initialized, ContainersReady, Ready, DisruptionTarget |
| restartPolicy | Always, OnFailure, Never; restarts in place with exponential backoff |
| CrashLoopBackOff | Display status: the kubelet is waiting before restarting a repeatedly failing container |
| Liveness probe | Restarts the container on repeated failure |
| Readiness probe | Removes the Pod from Service endpoints on failure |
| Startup probe | Gates liveness and readiness until the app has started |
| exec probe / httpGet probe / tcpSocket probe / grpc probe | The four probe mechanisms: command exit 0, HTTP 200–399, TCP connect, gRPC health SERVING |
| initialDelaySeconds, periodSeconds, timeoutSeconds, failureThreshold, successThreshold | Probe timing knobs; defaults 0, 10, 1, 3, 1 |
| Graceful termination | Deletion → endpoint removal and preStop → stop signal → drain → SIGKILL at the grace deadline |
| preStop hook | lifecycle.preStop (exec, httpGet, sleep): runs before the stop signal, inside the grace period |
| terminationGracePeriodSeconds | Seconds from deletion to SIGKILL (default 30); also per probe |
| SIGTERM / SIGKILL | Polite stop signal (or the image's STOPSIGNAL) / forced kill at the deadline |
| Endpoint removal | EndpointSlice conditions ready=false, terminating=true, serving during deletion |
| Readiness gates | Extra conditions in readinessGates that must be True for Ready |
| ReplicaSet | Keeps N Pods of one template; one per Deployment revision, labelled with pod-template-hash |
| Deployment | Manages ReplicaSets: rolling update or Recreate, revision history, rollback |
| Rolling update | Replacing Pods in steps bounded by maxSurge and maxUnavailable |
| Recreate | Strategy that deletes all old Pods before creating new ones |
| maxSurge / maxUnavailable | Extra Pods allowed (rounded up) / Pods allowed unavailable (rounded down); default 25% |
| minReadySeconds | Ready this long without crashing before a Pod counts as available |
| progressDeadlineSeconds | Seconds without progress before ProgressDeadlineExceeded (default 600) |
| revisionHistoryLimit | Old ReplicaSets/revisions kept for rollback (default 10) |
| rollout status / rollout undo / pause and resume | kubectl rollout subcommands: watch, roll back, batch template edits (pause only for Deployments) |
| StatefulSet | Pods with ordinal identity, stable DNS and per-Pod volumes, ordered changes |
| Stable network identity | Hostname name-N and DNS name-N.<service>.<ns>.svc via the headless Service |
| Ordinal index | 0..N-1 (or from ordinals.start); also the apps.kubernetes.io/pod-index label |
| volumeClaimTemplates | PVC templates; one claim per Pod (<template>-<pod>), retained by default |
| Headless Service | clusterIP: None: no virtual IP, DNS returns Pod addresses |
| podManagementPolicy | OrderedReady (default) or Parallel for StatefulSet scaling |
| Partition | StatefulSet rolling update updates only ordinals ≥ partition |
| DaemonSet | One Pod per selected node |
| Node selectors and tolerations preview | nodeSelector picks nodes by label; tolerations allow tainted nodes (scheduling chapter) |
| Job | Runs Pods to a number of successful completions |
| completions / parallelism | Successes required / Pods running at once |
| backoffLimit | Retries before the Job fails (default 6); backoffLimitPerIndex for Indexed Jobs |
| activeDeadlineSeconds | Wall-clock limit for a Job; takes precedence over backoffLimit |
| ttlSecondsAfterFinished | TTL controller deletes a finished Job and its Pods after this many seconds |
| Indexed Job | completionMode: Indexed: each Pod gets JOB_COMPLETION_INDEX 0..completions-1 |
| podFailurePolicy | Rules on exit codes or Pod conditions: FailJob, FailIndex, Ignore, Count |
| CronJob | Creates Jobs on a schedule (cron syntax, timeZone) |
| concurrencyPolicy | Allow, Forbid, Replace for overlapping CronJob runs |
| startingDeadlineSeconds | How late a missed CronJob run may still start |
| PodDisruptionBudget | Limits voluntary evictions (minAvailable or maxUnavailable) |
| HorizontalPodAutoscaler preview | Scales replicas from metrics (autoscaling/v2); details in the scheduling chapter |
| Pod topology spread preview | topologySpreadConstraints (maxSkew, topologyKey, whenUnsatisfiable) |
| Labels / selectors / matchLabels | Key/value tags / label queries / the map form of a selector (ANDed) |
| Immutable selector | spec.selector of apps/v1 controllers and Jobs cannot change after creation |
| imagePullPolicy | IfNotPresent, Always, Never; defaulted from tag or digest at creation |
| Image tags vs digests | Movable names vs content hashes (@sha256:) that pin exact bytes |
| Go health endpoints | /livez, /startupz, /readyz in the Go service, matching the three probes |
| Laravel queue worker Deployment | php artisan queue:work as its own Deployment with grace > --timeout |
| Laravel scheduler | schedule:run from a CronJob, or one schedule:work Pod; exactly one instance |
| php-fpm nginx sidecar vs two containers | Nginx as a native sidecar (ordered start/stop) vs two regular containers (arbitrary order) |
| process_control_timeout | php-fpm global setting: time limit for child processes to react to the master's signals (default 0) |
References
- Kubernetes Pods: https://kubernetes.io/docs/concepts/workloads/pods/ — Pod lifecycle: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/ — Termination of Pods: https://kubernetes.io/docs/concepts/workloads/pods/pod-termination/
- Init containers: https://kubernetes.io/docs/concepts/workloads/pods/init-containers/ — Sidecar containers: https://kubernetes.io/docs/concepts/workloads/pods/sidecar-containers/ — Ephemeral containers: https://kubernetes.io/docs/concepts/workloads/pods/ephemeral-containers/ — Disruptions: https://kubernetes.io/docs/concepts/workloads/pods/disruptions/ — Pod QoS: https://kubernetes.io/docs/concepts/workloads/pods/pod-qos/
- Probes (concept): https://kubernetes.io/docs/concepts/workloads/pods/probes/ — Configure probes (task): https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/ — Container lifecycle hooks: https://kubernetes.io/docs/concepts/containers/container-lifecycle-hooks/ — Images and pull policy: https://kubernetes.io/docs/concepts/containers/images/
- Controllers: Deployment https://kubernetes.io/docs/concepts/workloads/controllers/deployment/ — ReplicaSet https://kubernetes.io/docs/concepts/workloads/controllers/replicaset/ — StatefulSet https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/ — DaemonSet https://kubernetes.io/docs/concepts/workloads/controllers/daemonset/ — Job https://kubernetes.io/docs/concepts/workloads/controllers/job/ — CronJob https://kubernetes.io/docs/concepts/workloads/controllers/cron-jobs/ — TTL after finished https://kubernetes.io/docs/concepts/workloads/controllers/ttlafterfinished/
- Tasks and tutorials: stateless Deployment https://kubernetes.io/docs/tasks/run-application/run-stateless-application-deployment/ — replicated stateful application https://kubernetes.io/docs/tasks/run-application/run-replicated-stateful-application/ — StatefulSet basics https://kubernetes.io/docs/tutorials/stateful-application/basic-stateful-set/ — force delete StatefulSet Pods https://kubernetes.io/docs/tasks/run-application/force-delete-stateful-set-pod/ — configure a PDB https://kubernetes.io/docs/tasks/run-application/configure-pdb/ — safely drain a node https://kubernetes.io/docs/tasks/administer-cluster/safely-drain-node/ — update a DaemonSet https://kubernetes.io/docs/tasks/manage-daemon/update-daemon-set/ — pod failure policy https://kubernetes.io/docs/tasks/job/pod-failure-policy/ — Indexed Job https://kubernetes.io/docs/tasks/job/indexed-parallel-processing-static/ — debug running Pods https://kubernetes.io/docs/tasks/debug/debug-application/debug-running-pod/ — Pods and endpoint termination flow https://kubernetes.io/docs/tutorials/services/pods-and-endpoint-termination-flow/
- HPA (preview): https://kubernetes.io/docs/concepts/workloads/autoscaling/horizontal-pod-autoscale/ — walkthrough https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale-walkthrough/ — topology spread https://kubernetes.io/docs/concepts/scheduling-eviction/topology-spread-constraints/ — taints and tolerations https://kubernetes.io/docs/concepts/scheduling-eviction/taint-and-toleration/ — assigning Pods to nodes https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/ — API-initiated eviction https://kubernetes.io/docs/concepts/scheduling-eviction/api-eviction/ — node-pressure eviction https://kubernetes.io/docs/concepts/scheduling-eviction/node-pressure-eviction/ — resource management https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/
- Services: https://kubernetes.io/docs/concepts/services-networking/service/ — EndpointSlices: https://kubernetes.io/docs/concepts/services-networking/endpoint-slices/ — labels and selectors: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/ — recommended labels: https://kubernetes.io/docs/concepts/overview/working-with-objects/common-labels/ — well-known labels: https://kubernetes.io/docs/reference/labels-annotations-taints/
- API reference: Pod https://kubernetes.io/docs/reference/kubernetes-api/workload-resources/pod-v1/ — Deployment https://kubernetes.io/docs/reference/kubernetes-api/workload-resources/deployment-v1/ — StatefulSet https://kubernetes.io/docs/reference/kubernetes-api/workload-resources/stateful-set-v1/ — DaemonSet https://kubernetes.io/docs/reference/kubernetes-api/workload-resources/daemon-set-v1/ — Job https://kubernetes.io/docs/reference/kubernetes-api/workload-resources/job-v1/ — CronJob https://kubernetes.io/docs/reference/kubernetes-api/workload-resources/cron-job-v1/ — HPA v2 https://kubernetes.io/docs/reference/kubernetes-api/workload-resources/horizontal-pod-autoscaler-v2/ — PodDisruptionBudget https://kubernetes.io/docs/reference/kubernetes-api/policy-resources/pod-disruption-budget-v1/ — Service https://kubernetes.io/docs/reference/kubernetes-api/service-resources/service-v1/ — LabelSelector https://kubernetes.io/docs/reference/kubernetes-api/common-definitions/label-selector/ — PersistentVolumeClaim https://kubernetes.io/docs/reference/kubernetes-api/config-and-storage-resources/persistent-volume-claim-v1/
- kubectl: rollout https://kubernetes.io/docs/reference/kubectl/generated/kubectl_rollout/ — rollout status https://kubernetes.io/docs/reference/kubectl/generated/kubectl_rollout/kubectl_rollout_status/ — rollout undo https://kubernetes.io/docs/reference/kubectl/generated/kubectl_rollout/kubectl_rollout_undo/ — rollout pause https://kubernetes.io/docs/reference/kubectl/generated/kubectl_rollout/kubectl_rollout_pause/ — rollout history https://kubernetes.io/docs/reference/kubectl/generated/kubectl_rollout/kubectl_rollout_history/ — debug https://kubernetes.io/docs/reference/kubectl/generated/kubectl_debug/
- Feature gates (stages by version): https://kubernetes.io/docs/reference/command-line-tools-reference/feature-gates/ — releases: https://kubernetes.io/releases/
- Kubernetes blog: native sidecar containers (v1.28 alpha) https://kubernetes.io/blog/2023/08/25/native-sidecar-containers/ — v1.31 release https://kubernetes.io/blog/2024/08/13/kubernetes-v1-31-release/ — Pod failure policy GA https://kubernetes.io/blog/2024/08/19/kubernetes-1-31-pod-failure-policy-for-jobs-goes-ga/ — v1.33 release https://kubernetes.io/blog/2025/04/23/kubernetes-v1-33-release/ — backoff limit per index GA https://kubernetes.io/blog/2025/05/13/kubernetes-v1-33-jobs-backoff-limit-per-index-goes-ga/ — Job success policy GA https://kubernetes.io/blog/2025/05/15/kubernetes-1-33-jobs-success-policy-goes-ga/
- Example manifests (kubernetes/website): https://github.com/kubernetes/website/tree/main/content/en/examples
- gRPC health checking protocol: https://github.com/grpc/grpc/blob/master/doc/health-checking.md — grpc-go health server: https://github.com/grpc/grpc-go/blob/master/health/server.go
- Go:
net/httpserver source (Shutdown) https://go.dev/src/net/http/server.go —os/signalsource https://go.dev/src/os/signal/signal.go — Go 1.16 notes (NotifyContext) https://go.dev/doc/go1.16 — Go 1.22 notes (method patterns) https://go.dev/doc/go1.22 - Laravel 13: queues https://laravel.com/docs/13.x/queues — task scheduling https://laravel.com/docs/13.x/scheduling — deployment (health route) https://laravel.com/docs/13.x/deployment
- PHP-FPM configuration (process_control_timeout): https://www.php.net/manual/en/install.fpm.configuration.php — FPM signals (man page source) https://github.com/php/php-src/blob/master/sapi/fpm/php-fpm.8.in — php 8.4 fpm image Dockerfile (STOPSIGNAL SIGQUIT) https://github.com/docker-library/php/blob/master/8.4/trixie/fpm/Dockerfile
- Nginx: controlling nginx (signals) https://nginx.org/en/docs/control.html — official image Dockerfile (STOPSIGNAL SIGQUIT) https://github.com/nginx/docker-nginx/blob/master/stable/alpine-slim/Dockerfile
- Redis official image docs: https://github.com/docker-library/docs/tree/master/redis