Pods and containers
The Pod spec you write on the exam. Command and args, environment variables and the downward API, multi-container patterns, init containers, security contexts, Pod lifecycle and termination.
Exam tasks: 2.4 (primitives for robust, self-healing applications), 2.5 (Pod admission and scheduling), 2.2 (configuration into containers)
The decision: which fields of the Pod spec give this container the process, identity, configuration and companions the task describes, and which of those can still be changed after the Pod exists?
Almost every workload task is a Pod spec inside something else. Learn the spec once and Deployments, Jobs and DaemonSets are the same template with a controller around it.
Anatomy of a Pod
terminationGracePeriodSeconds. SIGTERM first, SIGKILL when it runs out.Pending, Running, Succeeded, Failed and Unknown.activeDeadlineSeconds, terminationGracePeriodSeconds and added tolerations can change, and CPU and memory can be resized in place.restartPolicy. Jobs need OnFailure or Never.k run web --image=nginx:1.27 --port=80 --labels=app=web -n shop # a Pod, not a Deployment
k run job-pod --image=busybox:1.36 --restart=Never -- sh -c 'echo hi; sleep 5'
k run web --image=nginx:1.27 $do > pod.yaml # generate YAML, then editCommand, args and environment
| Pod field | Replaces in the image | Note |
|---|---|---|
command | ENTRYPOINT | Runs without a shell. Use ["sh","-c","…"] for pipes and variables |
args | CMD | Set alone, it keeps the image's ENTRYPOINT |
env[].value | n/a | A literal value |
env[].valueFrom.configMapKeyRef / secretKeyRef | n/a | One key. Use envFrom for the whole object |
env[].valueFrom.fieldRef | n/a | The downward API: Pod fields such as metadata.name, status.podIP, spec.nodeName |
env[].valueFrom.resourceFieldRef | n/a | Container requests or limits, for example limits.memory |
containers:
- name: app
image: busybox:1.36
command: ["sh", "-c", "echo $POD_NAME on $NODE; sleep 3600"]
env:
- name: POD_NAME
valueFrom: { fieldRef: { fieldPath: metadata.name } }
- name: NODE
valueFrom: { fieldRef: { fieldPath: spec.nodeName } }$(VAR)incommandandargsis expanded by Kubernetes from the container'senv.$VARneeds a shell.- Environment variables are fixed when the container starts. Change them and the Pods must be recreated, which a Deployment does for you.
Exam signal
"Run sleep 3600 in the container" is command: ["sleep","3600"] or args: ["3600"] if the image's entrypoint is
sleep. When a task also needs the Pod's own name or IP inside the container, reach for the downward API instead of
a script.
Multi-container patterns
| Pattern | What the second container does | Shares |
|---|---|---|
| Sidecar | Runs for the whole life of the Pod: log shipper, proxy, config reloader | Network, volumes |
| Ambassador | Proxies the app's outbound connections, for example to a sharded database | localhost |
| Adapter | Reformats the app's output, for example to a metrics format | Volume or localhost |
| Init container | Runs first, to completion, then exits: wait for a service, run a migration, copy files | Volumes |
- Containers in a Pod reach each other on
localhostand cannot bind the same port. - Init containers run in order. If one fails, the kubelet retries it according to
restartPolicy, and the app containers never start. The Pod showsInit:0/2,Init:ErrororInit:CrashLoopBackOff. - A native sidecar is an init container with
restartPolicy: Always. It starts before the app, keeps running, and stops after it. Details are on the self-healing workloads page. - Containers share data through a volume both mount, usually
emptyDir. It lives as long as the Pod, and survives container restarts but not Pod deletion.
spec:
initContainers:
- name: wait-db
image: busybox:1.36
command: ["sh","-c","until nslookup db.shop.svc.cluster.local; do sleep 2; done"]
containers:
- name: app
image: nginx:1.27
volumeMounts: [{ name: html, mountPath: /usr/share/nginx/html }]
- name: refresher
image: busybox:1.36
command: ["sh","-c","while true; do date > /html/index.html; sleep 10; done"]
volumeMounts: [{ name: html, mountPath: /html }]
volumes:
- name: html
emptyDir: {}Security context
securityContext exists at the Pod level and at the container level. A container value wins over the Pod value.
| Setting | Level | Effect |
|---|---|---|
runAsUser, runAsGroup | Pod or container | Numeric IDs of the process |
runAsNonRoot: true | Pod or container | The kubelet refuses to start the container if it would run as UID 0 |
fsGroup | Pod | Group ownership applied to mounted volumes |
allowPrivilegeEscalation: false | Container | Blocks setuid binaries from gaining privileges |
readOnlyRootFilesystem: true | Container | The image's file system is read-only. Mount an emptyDir where it must write |
capabilities.drop: ["ALL"] and add | Container | Linux capabilities |
seccompProfile.type: RuntimeDefault | Pod or container | Default syscall filter |
privileged: true | Container | Full host access. Avoid it |
Pod Security Admission applies the Pod Security Standards (privileged, baseline, restricted) per namespace
through labels such as pod-security.kubernetes.io/enforce: restricted. A Pod that breaks the enforced level is
rejected at creation, so fix the Pod's securityContext instead of loosening the label.
runAsNonRoot with a root image
runAsNonRoot: true on an image whose user is root, with no runAsUser, fails with container has runAsNonRoot and image will run as root. Set runAsUser: 1000 (or any non-zero ID) as well.
Lifecycle and termination
- The API server stores the Pod. The scheduler binds it. The kubelet pulls images and runs init containers.
- The Pod is
Runningonce at least one container runs. It is Ready when all readiness probes pass, and only then do Services send it traffic. - On deletion, the Pod is marked
Terminatingand removed from Service endpoints. ThepreStophook runs, SIGTERM goes to each container, and afterterminationGracePeriodSecondsthe kubelet sends SIGKILL.
| Phase | Meaning |
|---|---|
Pending | Accepted, but not scheduled or still pulling images or running init containers |
Running | Bound to a node and at least one container is running or restarting |
Succeeded | All containers exited 0 and will not restart |
Failed | All containers ended and at least one failed |
Unknown | The node stopped reporting |
- A container in
CrashLoopBackOffis still aRunningPod. The phase is coarse. Read the container state and the Events ink describe pod. k delete pod web --force --grace-period=0removes the API object at once without waiting for the kubelet. Use it on the exam only to save time on stuck test Pods.
Fields you can change on a live Pod
k edit pod or k patch pod accepts only: spec.containers[*].image, spec.initContainers[*].image,
spec.activeDeadlineSeconds, spec.terminationGracePeriodSeconds, new tolerations, and metadata labels and annotations. CPU and memory requests and limits change only through the resize subresource (see autoscaling). For anything else:
k get pod web -o yaml > web.yaml # edit the file
k replace --force -f web.yaml # deletes and recreates the PodScenarios
Init:0/1 means zero of one init containers have completed. The Pod is scheduled, since the kubelet is already running the init container, and app containers start only after every init container exits successfully. Check the Service and DNS name that the loop waits for. An image pull error on the app container would show only after the init phase, and scheduling problems show as Pending with a FailedScheduling event.
The kubelet verifies a non-root user before starting. The image defaults to root and nothing sets a numeric user, so the container is rejected. A non-zero runAsUser satisfies the check. Removing the setting weakens the policy that was requested, privileged is the opposite of hardening, and the file system setting is unrelated.
All containers in a Pod share the Pod's IP and port space, so two processes cannot bind the same port. Reconfigure one of them. Services route to Pod ports and do not create separate namespaces, an init container would exit before the app runs, and hostNetwork would make the conflict worse by sharing the node's ports too.
Drill
kubectl config use-context cka-lab1
In namespace ledger, create a Pod audit with two containers. writer (busybox:1.36) appends the current date to
/data/audit.log every 5 seconds. reader (busybox:1.36) runs tail -F /data/audit.log. They share an emptyDir
volume. An init container prep must create /data/audit.log first. Run all containers as user 1000 with the root
file system read-only.
apiVersion: v1
kind: Pod
metadata:
name: audit
namespace: ledger
spec:
securityContext:
runAsUser: 1000
runAsNonRoot: true
initContainers:
- name: prep
image: busybox:1.36
command: ["sh","-c","touch /data/audit.log"]
volumeMounts: [{ name: data, mountPath: /data }]
securityContext: { readOnlyRootFilesystem: true }
containers:
- name: writer
image: busybox:1.36
command: ["sh","-c","while true; do date >> /data/audit.log; sleep 5; done"]
volumeMounts: [{ name: data, mountPath: /data }]
securityContext: { readOnlyRootFilesystem: true }
- name: reader
image: busybox:1.36
command: ["sh","-c","tail -F /data/audit.log"]
volumeMounts: [{ name: data, mountPath: /data }]
securityContext: { readOnlyRootFilesystem: true }
volumes:
- name: data
emptyDir: {}k create ns ledger
k apply -f audit.yaml
k logs audit -n ledger -c reader --tail=3Related
- Self-healing workloads: probes, restart policy and native sidecars.
- ConfigMaps and Secrets: the other sources of environment values.
- Resources and quotas: requests, limits and QoS classes.
- Troubleshooting applications: reading Pod status when the spec is wrong.
Further reading
Domain 2 · Workloads and scheduling
15% of the exam. Rolling out and rolling back Deployments, injecting configuration, autoscaling, self-healing controllers, and controlling where Pods land and how much they may use.
Deployments, rolling updates and rollbacks
How a Deployment rolls out a new revision through ReplicaSets, tuning maxSurge and maxUnavailable, Recreate, kubectl rollout history, undo, pause and restart, and spotting a stalled rollout.