Skip to content
Français
Sync not enabled: your progress stays in this browser My learning
Select theme
Français

Make an application 12-factor compliant on Kubernetes

By updated

Improve this page

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 preStop on 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.

FactorKubernetes object or settingObservable proofMeasured result
I. Codebasenone (Git repository)outside the clusternot checked by Kubernetes
II. Dependenciesself-contained imagedependencies bundled in the image, no installation at startuppodcli and curl come from the image
III. ConfigConfigMap, Secret, envFrompatch then rollout restartmessage changed in 2.95 s, image unchanged
IV. Backing servicesredis Service, PODINFO_CACHE_SERVER variablepoint to a second Redis404 on the other Redis, 200 on return
V. Build, release, runimage by digest, Deployment revisionsrollout history, undo5 revisions, undo renumbers
VI. ProcessesPod with no volume, state in Rediskubectl delete poddata intact
VII. Port bindingnamed port http, Servicewget http://podinfo/ from a Podthe application listens on 9898 itself
VIII. Concurrencyreplicaskubectl scale4 Pods Ready in under 2 s
IX. Disposabilityprobes, SIGTERM, preStopdeletion and rolling restart0 errors with preStop, 309 without
X. Dev/prod paritykustomize base and overlaysdiff of the two renderings4 differences, all declared
XI. Logscontainer stdoutkubectl logsone JSON line per event
XII. Admin processesJob, same image, same configkubectl waitJob 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.

The podinfo Deployment receives an image by digest, a ConfigMap and a Secret through envFrom, exposes a Service and calls Redis through a variable; the admin-seed Job reuses the same image and the same configuration.podinfo 6.15.0 imageby digestConfigMappodinfo-configDeployment podinfoSecretpodinfo-secret envFrom  envFrom Job admin-seed     Service podinfo     port 80 to http     Service redis     attached resource PODINFO_CACHE_SERVER  same image  same envFrom  same envFrom  writes the seed 
Source · SVG
Esc to close, + and − to zoom, scroll to move around. 100 %

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.

base/configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: podinfo-config
data:
PODINFO_UI_MESSAGE: "config v1 (base)"
PODINFO_UI_COLOR: "#34577c"
PODINFO_LEVEL: "info"
PODINFO_CACHE_SERVER: "tcp://redis:6379"
base/secret.yaml
apiVersion: v1
kind: Secret
metadata:
name: podinfo-secret
type: Opaque
stringData:
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.

base/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: podinfo
spec:
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 here

The podinfo Service routes port 80 to the named port http of the Deployment.

base/service.yaml
apiVersion: v1
kind: Service
metadata:
name: podinfo
spec:
selector:
app: podinfo
ports:
- name: http
port: 80
targetPort: http

The 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.

base/redis.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: redis
spec:
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: v1
kind: Service
metadata:
name: redis
spec:
selector:
app: redis
ports:
- name: redis
port: 6379
targetPort: redis

Two 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).

base/kustomization.yaml
resources:
- configmap.yaml
- secret.yaml
- deployment.yaml
- service.yaml
- redis.yaml
overlays/dev/kustomization.yaml
namespace: twelve-factor
resources:
- ../../base
patches:
- target:
kind: ConfigMap
name: podinfo-config
patch: |-
- op: replace
path: /data/PODINFO_UI_MESSAGE
value: "config v1 (dev)"
  1. Create the cluster with the pinned node image.

    Terminal window
    kind create cluster --name cn-12f --image kindest/node:v1.37.0@sha256:a1ed56cfb0e7b93589bdf97c8cd566405a265939e3620fc4f5de89adff580ae5

    Expected 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.

  2. Deploy the dev overlay, after creating the twelve-factor namespace (kustomize does not create it) and setting the context to it.

    Terminal window
    kubectl create namespace twelve-factor
    kubectl config set-context --current --namespace twelve-factor
    kubectl apply -k overlays/dev && kubectl rollout status deploy/redis deploy/podinfo
    configmap/podinfo-config created
    secret/podinfo-secret created
    service/podinfo created
    service/redis created
    deployment.apps/podinfo created
    deployment.apps/redis created
    deployment "redis" successfully rolled out
    deployment "podinfo" successfully rolled out

    Between the created and successfully rolled out lines, kubectl rollout status prints 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.

  3. Query the application with kubectl port-forward svc/podinfo 18080:80 in 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.

Terminal window
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.

Terminal window
kubectl rollout restart deploy/podinfo && kubectl rollout status deploy/podinfo
curl localhost:18080/ | grep -E 'message|hostname'
deployment.apps/podinfo restarted
deployment "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.

Terminal window
mkdir -p variants/generator
cp base/deployment.yaml base/service.yaml base/secret.yaml variants/generator/
variants/generator/kustomization.yaml
namespace: twelve-factor-gen
resources:
- deployment.yaml
- service.yaml
- secret.yaml
configMapGenerator:
- name: podinfo-config
literals:
- PODINFO_UI_MESSAGE=config hash v1
- PODINFO_UI_COLOR=#34577c
- PODINFO_LEVEL=info

Apply 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-gen
configmap/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/generator
configmap/podinfo-config-hbfbhm4t2f created
secret/podinfo-secret configured
service/podinfo unchanged
deployment.apps/podinfo configured
$ kubectl get cm -n twelve-factor-gen
podinfo-config-64hg4ffmkh 3 2s
podinfo-config-hbfbhm4t2f 3 1s

The 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.

Terminal window
kubectl rollout undo deploy/podinfo -n twelve-factor-gen
kubectl 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.

redis-b.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: redis-b
spec:
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: v1
kind: Service
metadata:
name: redis-b
spec:
selector:
app: redis-b
ports:
- name: redis-b
port: 6379
targetPort: redis-b

Before 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.

Terminal window
kubectl apply -f redis-b.yaml && kubectl rollout status deploy/redis-b
curl -X POST -d 'value-in-redis' localhost:18080/cache/my-key
curl localhost:18080/cache/my-key
kubectl 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:80
curl -i localhost:18080/cache/my-key

The 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.

Terminal window
kubectl set image deploy/podinfo podinfo=ghcr.io/stefanprodan/podinfo:6.14.1@sha256:f9537f729129d339aaef049b76ab2cd4ff06a424f99e5f6a5923c10621018fb1
kubectl annotate deploy/podinfo kubernetes.io/change-cause="release: podinfo 6.14.1 by digest" --overwrite
kubectl rollout history deploy/podinfo
REVISION CHANGE-CAUSE
1 <none>
2 <none>
3 <none>
4 <none>
5 release: podinfo 6.14.1 by digest

Revisions 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.

Terminal window
kubectl rollout undo deploy/podinfo
kubectl 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 back
ghcr.io/stefanprodan/podinfo:6.15.0@sha256:ec73780a8425...fa9da

The 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=podinfo
podinfo-665c8c5946-2mspq 1/1 Running 0 5s
$ curl localhost:18080/cache/my-key
value-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).

local-state.yaml
# ❌ avoid: hardcoded configuration and state on the Pod's local disk
apiVersion: apps/v1
kind: Deployment
metadata:
name: podinfo-local
spec:
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: v1
kind: Service
metadata:
name: podinfo-local
spec:
selector:
app: podinfo-local
ports:
- name: http
port: 80
targetPort: http

This 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.

Terminal window
kubectl apply -f local-state.yaml && kubectl rollout status deploy/podinfo-local
kubectl 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.

Terminal window
kubectl run client --image=busybox:1.37.0@sha256:a7dbc319b1438115a207e11930dc4bb3e643dcb3ec0bdd694bb36cd8fad289ec -- sleep 3600
kubectl wait --for=condition=Ready pod/client --timeout=60s
kubectl 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.

Terminal window
kubectl scale deploy/podinfo --replicas=4 && kubectl rollout status deploy/podinfo
for 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-zrd4s

On 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 namespace
deletion duration: 3275 ms

A 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.

ignore-sigterm.yaml
# ❌ avoid: PID 1 that ignores SIGTERM (sleep), 10 s grace period
apiVersion: v1
kind: Pod
metadata:
name: ignore-sigterm
spec:
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-sigterm
pod "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.

End of a Pod's life: the removal of the Service address and the deletion of the Pod start in parallel, then two cases for the kubelet. Without preStop, the kubelet sends SIGTERM immediately, while the Service still sends requests to the Pod. With preStop, it waits five seconds, the time for the address removal to propagate, then sends SIGTERM. In both cases, the grace period runs from the deletion.ContainerkubeletService(EndpointSlice)Control planeThe Service still sendsrequests to the PodThe removal spreadsduring these 5 salt[Without preStop][With preStop]par[Address removal][Pod deletion]Grace period:it starts with thedeletionRemoves the addressPod being deletedSIGTERM right awaypreStop: sleep 5SIGTERM
Source · SVG
Esc to close, + and − to zoom, scroll to move around. 100 %

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.

Terminal window
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.

ConfigurationSuccessful requestsErrors
without preStop8,738309 (3.4%)
with lifecycle.preStop: sleep 59,4120

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.

Terminal window
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.

job-admin.yaml
apiVersion: batch/v1
kind: Job
metadata:
name: admin-seed
spec:
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=90s
job.batch/admin-seed created
job.batch/admin-seed condition met
$ kubectl logs job/admin-seed
config 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/seed
seed-from-the-job

The 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).

overlays/prod/kustomization.yaml
namespace: twelve-factor-prod
resources:
- ../../base
patches:
- 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: 2

Before 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.

Terminal window
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.

SymptomCauseSolution
The application message does not change after kubectl patch cmVariables injected by envFrom are frozen when the container is createdkubectl rollout restart deploy/podinfo, or a ConfigMap named by hash
curl no longer answers after a rolloutA port-forward svc/... is bound to a single Pod, now goneRestart the port-forward
rollout undo leaves the new configurationThe ConfigMap changed by patch is not in the templateUse a configMapGenerator
kubectl apply -k brings the number of replicas back to 1The base value overwrites the kubectl scaleDeclare replicas in the overlay
8 requests out of 8 go to the same Pod right after scaleThe routing table is not propagated yetWait a few seconds before measuring
503 errors appear during a rolling restartAddress removal and SIGTERM happen in parallelAdd lifecycle.preStop (sleep 5 in the lab)
Deleting a Pod takes exactly the grace periodThe main process ignores SIGTERM, the kubelet waits then sends SIGKILLHave process 1 handle SIGTERM
/store answers 200 with a "code": 500 bodypodinfo returns the error in the JSONRead the response body, not the HTTP code
A kustomize generator does not suffix the ConfigMapbehavior: replace on a base ConfigMap produces no hashA directory that does not contain the base ConfigMap
kubectl logs deploy/podinfo gives the logs of a Pod that is shutting downThe Deployment has several Pods during the rolloutkubectl 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.

Terminal window
kind delete cluster --name cn-12f
Deleting 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 envFrom is 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 preStop avoids 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

6 questions
6 min
70% to pass

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