To make an application 12-factor compliant on Kubernetes, you do not tick a list: you measure, factor by factor, what the cluster guarantees and what it leaves to the application. This lesson deploys podinfo and Redis on a kind cluster, then audits each factor with a command and a real output: injected configuration, Redis replaceable by a variable, revision history, a Pod deleted without loss, graceful shutdown, logs, administration Job. It also shows measured counter-examples and names the factors that no Kubernetes object checks for you.
What you will learn
- Map each factor to the Kubernetes object or setting that carries it, in an audit grid.
- Prove that a configuration changes without touching the image, and that Redis is replaced by a variable.
- Read the history of a Deployment as the trace of releases.
- Delete a Pod to check that state lives elsewhere, and see what breaks when it lives on the Pod's disk.
- Measure the effect of SIGTERM and
preStopon a rolling restart. - Spot the factors that Kubernetes does not check on its own.
Prerequisites
The 12-factor methodology is a set of twelve rules for designing an application that is easy to deploy and operate in the cloud. Its presentation is in the lesson Cloud native principles: here, we do not redo it, we audit an application.
The Kubernetes objects used are assumed to be known: Deployment, Service, ConfigMap, Secret, probes, Job and rolling update. You need Docker, kind and kubectl locally, plus jq for a single log filter. The manifests are assembled with kustomize, built into kubectl (kubectl apply -k): the lesson Kustomize teaches this tool.
The durations and counters in the lesson come from real runs on a workstation, with kind v0.33.0, a kindest/node:v1.37.0 node and kubectl v1.36.0, which embeds kustomize v5.8.1. They give an order of magnitude, not a guaranteed value: take your own measurements.
Which factors does Kubernetes check, and which does it not?
Kubernetes carries most factors through a specific object, but it checks none of them for you. It applies what you declare: if the Pod's disk contains the application state, it does not detect it. The grid below serves as an audit plan. Each row gives the object or setting, the step that proves the factor and the result measured in the lab.
| Factor | Kubernetes object or setting | Observable proof | Measured result |
|---|---|---|---|
| I. Codebase | none (Git repository) | outside the cluster | not checked by Kubernetes |
| II. Dependencies | self-contained image | dependencies bundled in the image, no installation at startup | podcli and curl come from the image |
| III. Config | ConfigMap, Secret, envFrom | patch then rollout restart | message changed in 2.95 s, image unchanged |
| IV. Backing services | redis Service, PODINFO_CACHE_SERVER variable | point to a second Redis | 404 on the other Redis, 200 on return |
| V. Build, release, run | image by digest, Deployment revisions | rollout history, undo | 5 revisions, undo renumbers |
| VI. Processes | Pod with no volume, state in Redis | kubectl delete pod | data intact |
| VII. Port binding | named port http, Service | wget http://podinfo/ from a Pod | the application listens on 9898 itself |
| VIII. Concurrency | replicas | kubectl scale | 4 Pods Ready in under 2 s |
| IX. Disposability | probes, SIGTERM, preStop | deletion and rolling restart | 0 errors with preStop, 309 without |
| X. Dev/prod parity | kustomize base and overlays | diff of the two renderings | 4 differences, all declared |
| XI. Logs | container stdout | kubectl logs | one JSON line per event |
| XII. Admin processes | Job, same image, same config | kubectl wait | Job finished in 4.1 s |
Three factors escape the cluster. I (one repository per application) and II (explicitly declared and isolated dependencies) are judged in the repository and the Dockerfile, not in kubectl. X is half checkable: you compare what is deployed, but Kubernetes does not tell you whether your production Redis looks like the development one. The sections follow the order of the lab: factor X, which needs a second environment, comes last.
The diagram shows the audited application. Look at the two configuration sources entering the Deployment, Redis staying outside as an attached resource, and the administration Job that reuses the same image and the same configuration.
How do you set up the application to audit?
The lab fits in one kind cluster and one directory of kustomize manifests. The base contains a ConfigMap, a Secret, a podinfo Deployment, a Service, and a Redis Deployment with its Service. A dev overlay sets the twelve-factor namespace and the displayed message. The images are pinned by digest (the SHA-256 fingerprint of the image content, which cannot change under the same name), as everywhere on the site.
All the files of the lesson are saved in an empty working directory, laid out following the kustomize convention (a common base and overlays that modify it): create it with mkdir -p base overlays/dev overlays/prod. Each block below carries the path of the file to create.
The ConfigMap carries the non-sensitive settings, including the cache address. The Secret carries a lab value: a Secret is base64-encoded, not encrypted, and Kubernetes stores it unencrypted in etcd by default (encryption at rest is enabled separately). Never put a real value in an example.
apiVersion: v1kind: ConfigMapmetadata: name: podinfo-configdata: PODINFO_UI_MESSAGE: "config v1 (base)" PODINFO_UI_COLOR: "#34577c" PODINFO_LEVEL: "info" PODINFO_CACHE_SERVER: "tcp://redis:6379"apiVersion: v1kind: Secretmetadata: name: podinfo-secrettype: OpaquestringData: APP_API_TOKEN: "lab-token-non-secret-0001"The Deployment references the image by digest, injects the two objects with envFrom, names its port, declares two probes and provides a pause before shutdown (preStop). Each field serves a factor, detailed below. The preStop was only added when measuring factor IX: the earlier measurements do not depend on it.
apiVersion: apps/v1kind: Deploymentmetadata: name: podinfospec: replicas: 1 selector: matchLabels: app: podinfo template: metadata: labels: app: podinfo spec: terminationGracePeriodSeconds: 30 containers: - name: podinfo image: ghcr.io/stefanprodan/podinfo:6.15.0@sha256:ec73780a8425f59ea49f5bc8cdff0d598805a224fbaa1f86c67a244f250fa9da command: ["./podinfo"] ports: - name: http containerPort: 9898 envFrom: - configMapRef: name: podinfo-config - secretRef: name: podinfo-secret lifecycle: preStop: exec: command: ["sleep", "5"] readinessProbe: httpGet: path: /readyz port: http initialDelaySeconds: 1 periodSeconds: 2 livenessProbe: httpGet: path: /healthz port: http periodSeconds: 10 # resources: requests and limits, omitted hereThe podinfo Service routes port 80 to the named port http of the Deployment.
apiVersion: v1kind: Servicemetadata: name: podinfospec: selector: app: podinfo ports: - name: http port: 80 targetPort: httpThe Redis Deployment (image redis:7.4.11-alpine@sha256:858f009f9709ce576febc734aa78b8f6d624b82571f9ddb6bda4377c833b3499) is exposed by a redis Service on port 6379. Its readiness probe runs redis-cli ping.
apiVersion: apps/v1kind: Deploymentmetadata: name: redisspec: replicas: 1 selector: matchLabels: app: redis template: metadata: labels: app: redis spec: containers: - name: redis image: redis:7.4.11-alpine@sha256:858f009f9709ce576febc734aa78b8f6d624b82571f9ddb6bda4377c833b3499 ports: - name: redis containerPort: 6379 readinessProbe: exec: command: ["redis-cli", "ping"] periodSeconds: 2---apiVersion: v1kind: Servicemetadata: name: redisspec: selector: app: redis ports: - name: redis port: 6379 targetPort: redisTwo kustomization.yaml files assemble everything. The base lists the five files above. The dev overlay reuses the base, sets the twelve-factor namespace and replaces the ConfigMap message with a JSON patch (a list of replace operations on a precise path).
resources: - configmap.yaml - secret.yaml - deployment.yaml - service.yaml - redis.yamlnamespace: twelve-factorresources: - ../../basepatches: - target: kind: ConfigMap name: podinfo-config patch: |- - op: replace path: /data/PODINFO_UI_MESSAGE value: "config v1 (dev)"-
Create the cluster with the pinned node image.
Terminal window kind create cluster --name cn-12f --image kindest/node:v1.37.0@sha256:a1ed56cfb0e7b93589bdf97c8cd566405a265939e3620fc4f5de89adff580ae5Expected result:
Set kubectl context to "kind-cn-12f", in 9 to 11 s on the measurement workstation, the node image already being in the local cache. -
Deploy the dev overlay, after creating the
twelve-factornamespace (kustomize does not create it) and setting the context to it.Terminal window kubectl create namespace twelve-factorkubectl config set-context --current --namespace twelve-factorkubectl apply -k overlays/dev && kubectl rollout status deploy/redis deploy/podinfoconfigmap/podinfo-config createdsecret/podinfo-secret createdservice/podinfo createdservice/redis createddeployment.apps/podinfo createddeployment.apps/redis createddeployment "redis" successfully rolled outdeployment "podinfo" successfully rolled outBetween the
createdandsuccessfully rolled outlines,kubectl rollout statusprints waiting lines (Waiting for deployment ...) as long as the Pods are not ready. On the measurement workstation, pulled images included, the whole thing took 13 s to 27 s depending on the connection speed. -
Query the application with
kubectl port-forward svc/podinfo 18080:80in another terminal.$ curl localhost:18080/readyz{"status": "OK"}$ curl localhost:18080/ | grep -E 'hostname|version|message'"hostname": "podinfo-75f75b6644-5gzjj","version": "6.15.0","message": "config v1 (dev)",
The kubelet did pull the image by digest: the Pod's imageID field is ghcr.io/stefanprodan/podinfo@sha256:ec73780a...fa9da. A port-forward on a Service stays bound to a single Pod: restart it after each rollout, otherwise curl targets a Pod that is gone.
How do you manage configuration and secrets?
Factor III requires configuration to live in the environment, not in the image: on Kubernetes, that is the role of the ConfigMap and the Secret injected as variables. The test that proves the factor is to change a value without rebuilding anything. The application reads its settings from the PODINFO_* environment variables, supplied by envFrom. Change the value in the ConfigMap, then read back the message served by the application.
kubectl patch cm podinfo-config --type merge -p '{"data":{"PODINFO_UI_MESSAGE":"config v2 (dev)"}}'curl localhost:18080/ | grep -E 'message|hostname'configmap/podinfo-config patched "hostname": "podinfo-75f75b6644-5gzjj", "message": "config v1 (dev)",The message did not move: an environment variable injected by envFrom is frozen when the container is created. Changing the ConfigMap therefore does not change a Pod that is already running; you need a new Pod, which rollout restart produces. Since the Pod changes, restart the port-forward as well before the curl.
kubectl rollout restart deploy/podinfo && kubectl rollout status deploy/podinfocurl localhost:18080/ | grep -E 'message|hostname'deployment.apps/podinfo restarteddeployment "podinfo" successfully rolled out "hostname": "podinfo-665c8c5946-d59wf", "message": "config v2 (dev)",On the measurement workstation, the rollout took 2.95 s, and neither the image nor the code changed: this is what factor III expects. The Secret is injected the same way, and its value appears in podinfo's /env: never commit a Secret with a real value.
How do you trigger the rollout on its own when the configuration changes?
A kustomize configMapGenerator suffixes the ConfigMap name with a hash of its content, which ties the configuration to the Deployment revision. Changing a value creates a new ConfigMap, hence changes the Deployment template (kustomize itself replaces the name in the envFrom reference), hence triggers a rollout with no other action. The tested variant lives in a separate directory: it reuses the Deployment, the Service and the Secret, and generates the ConfigMap itself, in its own twelve-factor-gen namespace. It does not contain the base ConfigMap, because with behavior: replace on a ConfigMap inherited from the base, kustomize does not suffix the name with a hash.
mkdir -p variants/generatorcp base/deployment.yaml base/service.yaml base/secret.yaml variants/generator/namespace: twelve-factor-genresources: - deployment.yaml - service.yaml - secret.yamlconfigMapGenerator: - name: podinfo-config literals: - PODINFO_UI_MESSAGE=config hash v1 - PODINFO_UI_COLOR=#34577c - PODINFO_LEVEL=infoApply once, then change config hash v1 to config hash v2 in the file (with sed or an editor) and apply again. The suffixed names come from a hash of the content: with kustomize v5.8.1, you get the same ones if you reuse these values identically. In the output, look at the last two lines: two ConfigMaps coexist, and deployment.apps/podinfo configured shows that the template changed, so a rollout started.
$ kubectl create namespace twelve-factor-gen$ kubectl apply -k variants/generator ; kubectl get cm -n twelve-factor-genconfigmap/podinfo-config-64hg4ffmkh created...podinfo-config-64hg4ffmkh 3 1s$ sed -i 's/config hash v1/config hash v2/' variants/generator/kustomization.yaml$ kubectl apply -k variants/generatorconfigmap/podinfo-config-hbfbhm4t2f createdsecret/podinfo-secret configuredservice/podinfo unchangeddeployment.apps/podinfo configured$ kubectl get cm -n twelve-factor-genpodinfo-config-64hg4ffmkh 3 2spodinfo-config-hbfbhm4t2f 3 1sThe old ConfigMap is kept, and that is useful: kubectl rollout undo also restores the old configuration, since each revision points to its ConfigMap. To see it, run the undo, then list each Pod's ConfigMap.
kubectl rollout undo deploy/podinfo -n twelve-factor-genkubectl get pod -n twelve-factor-gen -o jsonpath='{range .items[*]}{.metadata.name} {.spec.containers[0].envFrom[0].configMapRef.name}{"\n"}{end}'During the rollback, a Pod still on the new ConfigMap sits alongside those on the old one. Once the rollback is finished, only one Pod remains, on the old one (podinfo-config-64hg4ffmkh).
How do you treat Redis as an attached resource?
Factor IV wants an external service to be a resource you replace with a configuration change, never a code change. Here, the application only knows Redis through PODINFO_CACHE_SERVER=tcp://redis:6379, that is, the DNS name of the redis Service. The test: deploy a second Redis (redis-b, with its Service), point the application at it through the ConfigMap, and observe.
The second Redis reuses the first one's manifest under the name redis-b. Save it in redis-b.yaml and deploy it in the lesson's namespace.
apiVersion: apps/v1kind: Deploymentmetadata: name: redis-bspec: replicas: 1 selector: matchLabels: app: redis-b template: metadata: labels: app: redis-b spec: containers: - name: redis-b image: redis:7.4.11-alpine@sha256:858f009f9709ce576febc734aa78b8f6d624b82571f9ddb6bda4377c833b3499 ports: - name: redis-b containerPort: 6379 readinessProbe: exec: command: ["redis-cli", "ping"] periodSeconds: 2---apiVersion: v1kind: Servicemetadata: name: redis-bspec: selector: app: redis-b ports: - name: redis-b port: 6379 targetPort: redis-bBefore switching Redis, you need a value to find again: write my-key in the first Redis (the port-forward from step 3 must be running; restart it if a rollout interrupted it). Then switch the ConfigMap to redis-b, restart the port-forward (a rollout replaced the Pod) and read the key again.
kubectl apply -f redis-b.yaml && kubectl rollout status deploy/redis-bcurl -X POST -d 'value-in-redis' localhost:18080/cache/my-keycurl localhost:18080/cache/my-keykubectl patch cm podinfo-config --type merge -p '{"data":{"PODINFO_CACHE_SERVER":"tcp://redis-b:6379"}}'kubectl rollout restart deploy/podinfo && kubectl rollout status deploy/podinfo# restart the port-forward: kubectl port-forward svc/podinfo 18080:80curl -i localhost:18080/cache/my-keyThe my-key key returns value-in-redis before the change, then answers 404: the application is now talking to another, empty service. A write curl -X POST -d 'value-b' localhost:18080/cache/key-b is stored in the second Redis: kubectl exec deploy/redis-b -- redis-cli keys '*' lists key-b, while deploy/redis contains my-key. In both cases a key named after the Pod also appears, which podinfo stores itself at startup: ignore it.
After going back to tcp://redis:6379 (same patch, same rollout restart), /cache/my-key returns value-in-redis again with a 200, and /cache/key-b returns 404. No change to the code, the image or the Deployment: only a variable. Not tested here: Redis authentication, persistence and high availability.
What does the Deployment history show for build, release and run?
Factor V separates building (the image), publishing a release (image plus configuration) and running (the Pods). On Kubernetes, the image is referenced by digest, and the release is the Deployment template: each template change creates a revision. The history is therefore the trace of releases, provided you document it.
To test, we switch the image to the previous podinfo version (6.14.1, by digest) and annotate the cause of the change.
kubectl set image deploy/podinfo podinfo=ghcr.io/stefanprodan/podinfo:6.14.1@sha256:f9537f729129d339aaef049b76ab2cd4ff06a424f99e5f6a5923c10621018fb1kubectl annotate deploy/podinfo kubernetes.io/change-cause="release: podinfo 6.14.1 by digest" --overwritekubectl rollout history deploy/podinfoREVISION CHANGE-CAUSE1 <none>2 <none>3 <none>4 <none>5 release: podinfo 6.14.1 by digestRevisions 2, 3 and 4 are rollout restart runs (the message change, the switch to redis-b, the return to redis), not image releases: the history mixes everything, hence the value of the kubernetes.io/change-cause annotation. After the switch (restart the port-forward), curl localhost:18080/ gives "version": "6.14.1" and the message config v2 (dev): the configuration followed, the image changed.
kubectl rollout undo deploy/podinfokubectl get deploy podinfo -o jsonpath='{.spec.template.spec.containers[0].image}'Warning: resource deployments/podinfo was previously managed with 'kubectl apply'. Rolling back will not update the kubectl.kubernetes.io/last-applied-configuration annotation...deployment.apps/podinfo rolled backghcr.io/stefanprodan/podinfo:6.15.0@sha256:ec73780a8425...fa9daThe warning says that the Deployment was created by kubectl apply, which keeps its last configuration in an annotation; the rollback leaves it stale. Two other facts matter. First, undo renumbers the revisions: the old revision 4 becomes 6, and its cause is empty. Second, it does not undo a ConfigMap changed by patch, since the latter is not in the template; only a ConfigMap named by hash comes back with the undo.
# ❌ avoid: changing the configuration by patch and believing rollout undo restores it$ kubectl patch cm podinfo-config --type merge -p '{"data":{"PODINFO_UI_MESSAGE":"config v2 (dev)"}}'$ kubectl rollout undo deploy/podinfo # the image comes back, the message stays "config v2 (dev)"Last pitfall: the repository stays the source of truth of the release. Replaying kubectl apply -k overlays/dev puts the repository values back in the cluster: the ConfigMap message becomes config v1 (dev) again, and replicas goes back to 1, even after a kubectl scale like the one in the section on concurrency. If you replay it, redo the patch to config v2 (dev) before the following sections.
How do you prove that a process is stateless?
Factors VI, VII and VIII are checked together: a stateless process that listens on a port by itself is multiplied simply by increasing the number of Pods. The central test is the bluntest one, deleting a Pod and seeing whether anything is lost. To go deeper into loose coupling and stateless design, see Loose coupling and stateless design (in French).
What happens to the data when you delete the Pod?
If state lives in an attached service, deleting the Pod loses nothing. We write a value in the cache, read it back, then delete the Pod that served it.
$ curl -X POST -d 'value-in-redis' localhost:18080/cache/my-key # [202]$ kubectl delete pod -l app=podinfo # about 9 s with the preStop$ kubectl get pods -l app=podinfopodinfo-665c8c5946-2mspq 1/1 Running 0 5s$ curl localhost:18080/cache/my-keyvalue-in-redis # [200]The Deployment recreated a Pod with a different name, and the value is still there, since it lives in Redis. Restart the port-forward before the last command: the previous one targeted the deleted Pod. Limit: the lab's Redis has no volume or persistence, and deleting its Pod would lose the data (not tested). It is a cache, not a source of truth.
What is the effect of state kept on the Pod's disk?
State written in the Pod's file system disappears with it. The counter-example is deliberately faulty: configuration hardcoded in the arguments, and an emptyDir volume mounted on /data (an empty volume created with the Pod and destroyed with it).
# ❌ avoid: hardcoded configuration and state on the Pod's local diskapiVersion: apps/v1kind: Deploymentmetadata: name: podinfo-localspec: replicas: 1 selector: matchLabels: app: podinfo-local template: metadata: labels: app: podinfo-local spec: containers: - name: podinfo image: ghcr.io/stefanprodan/podinfo:6.15.0@sha256:ec73780a8425f59ea49f5bc8cdff0d598805a224fbaa1f86c67a244f250fa9da command: ["./podinfo", "--ui-message=hardcoded in args", "--data-path=/data"] ports: - name: http containerPort: 9898 volumeMounts: - name: data mountPath: /data volumes: - name: data emptyDir: {}---apiVersion: v1kind: Servicemetadata: name: podinfo-localspec: selector: app: podinfo-local ports: - name: http port: 80 targetPort: httpThis volume is indispensable: the 6.15.0 image has no /data, and without it POST /store answers {"code":500,"message":"writing file failed"} (with an HTTP code 200). With it, the write succeeds, then we delete the Pod. Apply the file, wait for the deployment, then open a port-forward on port 18081 so as not to disturb the podinfo one.
kubectl apply -f local-state.yaml && kubectl rollout status deploy/podinfo-localkubectl port-forward svc/podinfo-local 18081:80 # in another terminal$ curl -w ' [%{http_code}]\n' -X POST -d 'state-on-local-disk' localhost:18081/store{ "hash": "b0f16459feb69318ca4c6dca5ded6ab0c5d5c073"} [202]$ kubectl delete pod -l app=podinfo-local$ kubectl port-forward svc/podinfo-local 18081:80 # restarted: the Pod changed$ curl -w ' [%{http_code}]\n' localhost:18081/store/b0f16459feb69318ca4c6dca5ded6ab0c5d5c073{ "code": 500, "message": "reading file failed"} [200]The data disappeared with the Pod. Two errors add up: the state is not in an attached service (factor VI), and the message comes from the arguments, so changing the ConfigMap would not reach it (factor III). The number in square brackets is the HTTP code displayed by curl -w: podinfo answers with a code 200 or 202 and a JSON that carries "code": 500, so read the response body, not the code. Then remove the counter-example with kubectl delete -f local-state.yaml, before continuing.
How do you check port binding and concurrency?
Factor VII wants the application to listen on its port by itself, with no injected web server; factor VIII, that you multiply it by the number of processes. The port is named in the Deployment, and the Service translates port 80 to that name. From a client Pod, access goes through the Service name.
The client Pod is a busybox (busybox:1.37.0@sha256:a7dbc319b1438115a207e11930dc4bb3e643dcb3ec0bdd694bb36cd8fad289ec) started with sleep 3600. You create it first, then wait for it to be ready.
kubectl run client --image=busybox:1.37.0@sha256:a7dbc319b1438115a207e11930dc4bb3e643dcb3ec0bdd694bb36cd8fad289ec -- sleep 3600kubectl wait --for=condition=Ready pod/client --timeout=60skubectl get deploy podinfo -o jsonpath='{.spec.template.spec.containers[0].ports}'kubectl exec client -- wget -qO- http://podinfo.twelve-factor.svc.cluster.local/readyz[{"containerPort":9898,"name":"http","protocol":"TCP"}]{ "status": "OK"}The first line of the output shows the Deployment's named port http; the second confirms that the Service answers from another Pod, by its name. To list the addresses behind the Service, prefer kubectl get endpointslice: kubectl get endpoints prints Warning: v1 Endpoints is deprecated in v1.33+.
For concurrency, we move to 4 replicas and send 20 requests.
kubectl scale deploy/podinfo --replicas=4 && kubectl rollout status deploy/podinfofor i in $(seq 1 20); do kubectl exec client -- wget -qO- http://podinfo/ | grep -oE 'podinfo-[a-z0-9]+-[a-z0-9]+'; done | sort | uniq -c 10 podinfo-66647cfb45-9dx87 1 podinfo-66647cfb45-bgcj6 4 podinfo-66647cfb45-zgz42 5 podinfo-66647cfb45-zrd4sOn the measurement workstation, the 4 Pods were Ready in under 2 s with the image already on the node (the readiness probe waits 1 s), and all 4 receive traffic. The distribution is not equal over 20 requests, which is normal. Started one second after the scale, the same loop sent 8 requests out of 8 to the same Pod: routing takes a few seconds to propagate, wait before measuring. Automatic adjustment of the number of Pods is not tested here, it belongs to horizontal autoscaling.
Kubernetes also injects into the Pods, for each Service, variables such as PODINFO_SERVICE_HOST. Since the Service is called podinfo and podinfo reads the variables prefixed PODINFO_, the names cross: nothing broke here (the port stayed 9898), but it is a naming pitfall. The enableServiceLinks: false field of the Pod spec removes these variables (not tested here).
Is a Pod really disposable?
Factor IX asks for a fast start and a clean stop: Kubernetes destroys and recreates Pods all the time, the application must survive it without losing a request. Three measurements show it: the startup, the reaction to SIGTERM (the stop signal that Kubernetes sends to the container's main process), then a rolling restart under load.
For startup, the Kubernetes timestamps give this: the replacement Pod, created at 12:48:47Z when the old one received SIGTERM, was Ready at 12:48:48Z, about 1 s (image already on the node, one-second resolution).
At shutdown, kubectl delete pod sends SIGTERM to the main process, and podinfo closes its HTTP server. To read the shutdown line, follow the Pod's logs in a second terminal (kubectl logs -f <pod>) while you delete it. The measurement below was made before the preStop was added: with this lesson's Deployment, the deletion takes 5 s longer (replayed: about 4 s without preStop, 9 to 11 s with).
SIGTERM sent at 12:48:47.112{"level":"info","ts":"2026-10-13T12:48:47.147Z","caller":"signals/shutdown.go:55","msg":"Shutting down HTTP/HTTPS server","timeout":5}pod "podinfo-66647cfb45-zrd4s" deleted from twelve-factor namespacedeletion duration: 3275 msA probe run every 0.45 s on the Pod's IP during the shutdown receives 503 on /readyz from the first request and for 3.3 s, then the connection is refused: podinfo declares itself not ready as soon as SIGTERM arrives, waits about 3 s, then closes. The counter-example is a process that ignores SIGTERM. The lesson Container lifecycle, PID 1 and graceful shutdown explains why a container's process 1 handles signals separately; here, we only measure what it costs on Kubernetes.
# ❌ avoid: PID 1 that ignores SIGTERM (sleep), 10 s grace periodapiVersion: v1kind: Podmetadata: name: ignore-sigtermspec: terminationGracePeriodSeconds: 10 containers: - name: sleeper image: busybox:1.37.0@sha256:a7dbc319b1438115a207e11930dc4bb3e643dcb3ec0bdd694bb36cd8fad289ec command: ["sleep", "3600"]Save this Pod in ignore-sigterm.yaml, apply it, wait for it to be ready, then measure its deletion with time.
$ kubectl apply -f ignore-sigterm.yaml && kubectl wait --for=condition=Ready pod/ignore-sigterm$ time kubectl delete pod ignore-sigtermpod "ignore-sigterm" deleted from twelve-factor namespace(duration reported by time: 11.4 s)The deletion took 11.4 s: the kubelet waits for the end of the grace period (terminationGracePeriodSeconds, 10 s here), then sends SIGKILL, which kills the process without letting it finish. A process deaf to SIGTERM makes every rollout as long as the grace period, and cuts in-flight requests.
Why add a preStop during a rolling restart?
At the end of a Pod's life, removing its addresses from the Service and sending SIGTERM happen in parallel: requests can still arrive on a Pod that already answers 503. The preStop hook runs before SIGTERM and delays it by a few seconds, the time for the removal to propagate.
The diagram starts with a parallel block: the removal of the address from the Service and the deletion of the Pod start at the same time. It then shows the kubelet's two paths. In the "Without preStop" branch, SIGTERM goes out immediately. In the "With preStop" branch, the kubelet first waits five seconds. The last note matters too: the grace period runs from the deletion, preStop included.
The grace period (terminationGracePeriodSeconds: 30) therefore includes the preStop: preStop plus normal shutdown must fit in these 30 s. To measure the effect, a wget /healthz loop runs for 25 s from the client Pod, on 3 replicas, with a rollout restart started at t+2 s. For the "without preStop" row, remove the lifecycle block from the Deployment.
kubectl scale deploy/podinfo --replicas=3 && kubectl rollout status deploy/podinfo(sleep 2; kubectl rollout restart deploy/podinfo) &kubectl exec client -- sh -c 'ok=0; ko=0; end=$(( $(date +%s) + 25 )); while [ $(date +%s) -lt $end ]; do if wget -qO- -T 2 http://podinfo/healthz >/dev/null 2>&1; then ok=$((ok+1)); else ko=$((ko+1)); fi; done; echo "ok=$ok errors=$ko"'The loop runs in the client Pod for 25 s and prints the number of successful responses and errors. To remove the preStop, kubectl patch deploy podinfo --type json -p '[{"op":"remove","path":"/spec/template/spec/containers/0/lifecycle"}]' is enough; kubectl apply -k overlays/dev puts it back. On the measurement workstation, two runs with preStop gave errors=0, and two runs without gave 300 to 352 errors. The request totals depend on the machine, the order of magnitude stays the same. The table details the first series.
| Configuration | Successful requests | Errors |
|---|---|---|
without preStop | 8,738 | 309 (3.4%) |
with lifecycle.preStop: sleep 5 | 9,412 | 0 |
Without the pause, 3.4% of requests failed during the rollout; with five seconds of sleep, none. Each row of the table is a single run, with no statistics: the result shows the mechanism and an order of magnitude, not a guaranteed rate.
The exec action with sleep assumes a sleep binary in the image. A distroless image does not contain one: Kubernetes then provides a native action, lifecycle.preStop.sleep.seconds: 5, stable since Kubernetes 1.34, which waits without starting a process in the container.
Another pitfall: kubectl logs deploy/podinfo during a rollout can land on the Pod that is shutting down (Found 2 pods, using pod/...). Prefer kubectl logs -l app=podinfo.
Where do the logs go?
Factor XI wants the application to write its events to standard output, and leave the platform to collect them. Podinfo writes one JSON line per event to stdout, no file. kubectl logs reads them directly.
kubectl logs -l app=podinfo --tail=20{"level":"info","ts":"2026-10-13T12:53:02.747Z","caller":"podinfo/main.go:170","msg":"Starting podinfo","version":"6.15.0","revision":"dd507173...","port":"9898"}{"level":"info","ts":"...","caller":"http/server.go:273","msg":"Starting HTTP Server.","addr":":9898"}Each line carries the level, the time, the caller and the message, which makes it easy to filter. To diagnose a Pod beyond these lines, see Debugging a Kubernetes application.
At the info level, requests are not logged. Switching to PODINFO_LEVEL=debug requires a configuration change and a rollout, which replays factor III: one JSON line per request then appears, with for example "uri":"/readyz" and the kube-probe/1.37 agent. A filter is enough to count the levels: kubectl logs -l app=podinfo --tail=50 | jq -r .level | sort | uniq -c gave 15 debug and 2 info in the lab. Routing to a collection system is not tested: the application does not deal with it, that is the contract of factor XI.
How do you run an administration task?
Factor XII wants one-off tasks (migration, data seed) to run as separate processes, with the same code and the same configuration as the application. On Kubernetes, that is a Job. The lab's Job reuses the image by digest, the same envFrom, and the podcli and curl tools provided by the image. It writes a value in the cache. Save it in job-admin.yaml.
apiVersion: batch/v1kind: Jobmetadata: name: admin-seedspec: backoffLimit: 0 ttlSecondsAfterFinished: 600 template: spec: restartPolicy: Never containers: - name: admin image: ghcr.io/stefanprodan/podinfo:6.15.0@sha256:ec73780a8425f59ea49f5bc8cdff0d598805a224fbaa1f86c67a244f250fa9da envFrom: - configMapRef: name: podinfo-config - secretRef: name: podinfo-secret command: - sh - -c - | set -e echo "config seen by the Job: message=$PODINFO_UI_MESSAGE cache=$PODINFO_CACHE_SERVER token=${#APP_API_TOKEN} characters" podcli check tcp "${PODINFO_CACHE_SERVER#tcp://}" curl -fsS -X POST -d "seed-from-the-job" http://podinfo/cache/seed echo "seed written"The script prints the length of the secret, never its value. ttlSecondsAfterFinished: 600 cleans the Job up ten minutes after it ends. It does not belong to the kustomize base, because a Job is immutable: its template can no longer be modified after creation.
$ kubectl apply -f job-admin.yaml && kubectl wait --for=condition=complete job/admin-seed --timeout=90sjob.batch/admin-seed createdjob.batch/admin-seed condition met$ kubectl logs job/admin-seedconfig seen by the Job: message=config v2 (dev) cache=tcp://redis:6379 token=25 characters... check succeed {"address": "redis:6379"}seed written$ kubectl exec client -- wget -qO- http://podinfo/cache/seedseed-from-the-jobThe Job saw the same configuration as the Deployment, reached the same Redis and wrote a value that the application reads back: kubectl get job admin-seed shows Complete 1/1 in 4 s. Same image, same configuration, separate process: that is factor XII.
To avoid, without having measured it here: running the same task by hand with kubectl exec in a running Pod, because it is neither traced nor replayable, and depends on the state of that Pod.
Are dev and prod really identical?
Factor X asks to keep development and production as close as possible: same artifact, different configuration. Here, a common base and two kustomize overlays produce two namespaces. The check is a diff of the two renderings. The prod overlay looks like dev: same base, another namespace, and three changed values (log level, message, number of replicas).
namespace: twelve-factor-prodresources: - ../../basepatches: - target: kind: ConfigMap name: podinfo-config patch: |- - op: replace path: /data/PODINFO_UI_MESSAGE value: "config v1 (prod)" - op: replace path: /data/PODINFO_LEVEL value: "warn" - target: kind: Deployment name: podinfo patch: |- - op: replace path: /spec/replicas value: 2Before comparing, deploy prod (create its namespace first, as for dev): kubectl create namespace twelve-factor-prod && kubectl apply -k overlays/prod. The diff returns exit code 1 when the renderings differ: that is the expected result here.
diff <(kubectl kustomize overlays/dev) <(kubectl kustomize overlays/prod)kubectl get deploy -A -o 'custom-columns=NS:.metadata.namespace,NAME:.metadata.name,IMAGE:.spec.template.spec.containers[0].image'The diff only shows four differences: the log level, the message, the namespace and replicas (1 against 2). The two podinfo Deployments carry the same image by digest (ghcr.io/stefanprodan/podinfo:6.15.0@sha256:ec73780a...fa9da), and Redis is identical. In twelve-factor-prod, kubectl get pods lists 2 podinfo Pods and 1 Redis.
This test compares manifests, not real environments. Kubernetes does not tell you whether the production Redis has the same version, the same persistence or the same load as the development one. Factor X remains a team discipline, which the tool only makes verifiable on the declared objects.
Troubleshooting
These symptoms are the ones met during the lab.
| Symptom | Cause | Solution |
|---|---|---|
The application message does not change after kubectl patch cm | Variables injected by envFrom are frozen when the container is created | kubectl rollout restart deploy/podinfo, or a ConfigMap named by hash |
curl no longer answers after a rollout | A port-forward svc/... is bound to a single Pod, now gone | Restart the port-forward |
rollout undo leaves the new configuration | The ConfigMap changed by patch is not in the template | Use a configMapGenerator |
kubectl apply -k brings the number of replicas back to 1 | The base value overwrites the kubectl scale | Declare replicas in the overlay |
8 requests out of 8 go to the same Pod right after scale | The routing table is not propagated yet | Wait a few seconds before measuring |
| 503 errors appear during a rolling restart | Address removal and SIGTERM happen in parallel | Add lifecycle.preStop (sleep 5 in the lab) |
| Deleting a Pod takes exactly the grace period | The main process ignores SIGTERM, the kubelet waits then sends SIGKILL | Have process 1 handle SIGTERM |
/store answers 200 with a "code": 500 body | podinfo returns the error in the JSON | Read the response body, not the HTTP code |
| A kustomize generator does not suffix the ConfigMap | behavior: replace on a base ConfigMap produces no hash | A directory that does not contain the base ConfigMap |
kubectl logs deploy/podinfo gives the logs of a Pod that is shutting down | The Deployment has several Pods during the rollout | kubectl logs -l app=podinfo or name the Pod |
Clean up the lab
First stop the kubectl port-forward commands still open (Ctrl+C in their terminal). The kind cluster is disposable: deleting it removes all the lab objects.
kind delete cluster --name cn-12fDeleting cluster "cn-12f" ...Deleted nodes: ["cn-12f-control-plane"]Put it into practice
The lab gives you a podinfo application whose configuration is hardcoded in its arguments, whose state is written on a Pod volume and which has no clean shutdown, while a Redis runs next to it without being used. You generate the configuration with a Kustomize configMapGenerator, you move the state into Redis, you add a preStop hook, then you plant the cache seed with an administration Job. The validation checks four results: a generated ConfigMap (name suffixed with a hash) injected by envFrom, no local state volume with a cache value that survives the Pod deletion, a preStop on the podinfo container, and a finished admin-seed Job, which uses the application image and wrote the seed in Redis. The measurements in this lesson are on podinfo 6.15.0, while the lab plays the most recent version, 6.17.0. You start it with dsoxlab run k8s-rendre-une-application-conforme-12-facteurs, then dsoxlab check k8s-rendre-une-application-conforme-12-facteurs reads the cluster state and returns the result of each criterion.
Key points
- Kubernetes carries the factors through objects (ConfigMap, Secret, Service, Job, probes), but it checks nothing: it is up to you to prove each factor with a command.
- Factors I and II are judged in the repository and the image, not in the cluster; X is only checked on the manifests.
- A variable injected by
envFromis frozen when the container is created: changing the ConfigMap needs a new Pod, and a ConfigMap name suffixed with a hash ties configuration and revision. - An external service is an attached resource when changing a variable is enough to replace it.
- A Pod must be deletable without loss: state lives in an attached service, never on the Pod's disk.
- A process that ignores SIGTERM makes deletion as long as the grace period; a
preStopavoids errors while the Pod is removed from the Service (309 errors out of 9,047 requests without, 0 with, on the first series of measurements). - A Job that reuses the application's image and configuration is the Kubernetes form of an administration task.
Knowledge check
Check what you have learned with this interactive quiz
How it works
- The timer starts when you click Start
- Multiple choice, true/false and short answer questions
- You can move between questions
- Detailed results are shown at the end
Starts the quiz and the timer
Review
(0/0)Result saved on this device. It will be sent to your account at the next sync. Sync now
Score by domain
A domain groups several guides and gets several questions, so its score is more reliable than a per-topic score, which often rests on a single question.
Summary
Strengths
No topic passed at 80% on at least two questions yet.
Weak areas
No topic below the pass mark.
Recommended next
Hints before you try again?
Continue the course: Pod Networking: how Pods talk to each other across nodes
A new full quiz with random questions
Work again only on the questions you missed