Skip to Content
Asterrr's Handbook

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

kubelet NodePod: one IP, shared volumesin orderstarts and restartsInit container1: wait for thedatabaseInit container2: fetch configApp containerSidecar: shipslogs or proxiestrafficemptyDir volumekubelet
One Pod, three kinds of container. Init containers run one at a time to completion, then the app and its sidecar start together and share the network and volumes.
30 s
Default terminationGracePeriodSeconds. SIGTERM first, SIGKILL when it runs out.
5 phases
Pending, Running, Succeeded, Failed and Unknown.
Few fields
Most of a Pod spec is immutable. Images, activeDeadlineSeconds, terminationGracePeriodSeconds and added tolerations can change, and CPU and memory can be resized in place.
Always
Default restartPolicy. Jobs need OnFailure or Never.
1 IP
All containers in a Pod share one network namespace.
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 edit

Command, args and environment

Pod fieldReplaces in the imageNote
commandENTRYPOINTRuns without a shell. Use ["sh","-c","…"] for pipes and variables
argsCMDSet alone, it keeps the image's ENTRYPOINT
env[].valuen/aA literal value
env[].valueFrom.configMapKeyRef / secretKeyRefn/aOne key. Use envFrom for the whole object
env[].valueFrom.fieldRefn/aThe downward API: Pod fields such as metadata.name, status.podIP, spec.nodeName
env[].valueFrom.resourceFieldRefn/aContainer 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) in command and args is expanded by Kubernetes from the container's env. $VAR needs 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

PatternWhat the second container doesShares
SidecarRuns for the whole life of the Pod: log shipper, proxy, config reloaderNetwork, volumes
AmbassadorProxies the app's outbound connections, for example to a sharded databaselocalhost
AdapterReformats the app's output, for example to a metrics formatVolume or localhost
Init containerRuns first, to completion, then exits: wait for a service, run a migration, copy filesVolumes
  • Containers in a Pod reach each other on localhost and 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 shows Init:0/2, Init:Error or Init: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.

SettingLevelEffect
runAsUser, runAsGroupPod or containerNumeric IDs of the process
runAsNonRoot: truePod or containerThe kubelet refuses to start the container if it would run as UID 0
fsGroupPodGroup ownership applied to mounted volumes
allowPrivilegeEscalation: falseContainerBlocks setuid binaries from gaining privileges
readOnlyRootFilesystem: trueContainerThe image's file system is read-only. Mount an emptyDir where it must write
capabilities.drop: ["ALL"] and addContainerLinux capabilities
seccompProfile.type: RuntimeDefaultPod or containerDefault syscall filter
privileged: trueContainerFull 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

  1. The API server stores the Pod. The scheduler binds it. The kubelet pulls images and runs init containers.
  2. The Pod is Running once at least one container runs. It is Ready when all readiness probes pass, and only then do Services send it traffic.
  3. On deletion, the Pod is marked Terminating and removed from Service endpoints. The preStop hook runs, SIGTERM goes to each container, and after terminationGracePeriodSeconds the kubelet sends SIGKILL.
PhaseMeaning
PendingAccepted, but not scheduled or still pulling images or running init containers
RunningBound to a node and at least one container is running or restarting
SucceededAll containers exited 0 and will not restart
FailedAll containers ended and at least one failed
UnknownThe node stopped reporting
  • A container in CrashLoopBackOff is still a Running Pod. The phase is coarse. Read the container state and the Events in k describe pod.
  • k delete pod web --force --grace-period=0 removes 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 Pod

Scenarios

Scenario
A Pod has an init container that runs 'until nslookup db; do sleep 2; done' and an app container. The Pod shows STATUS Init:0/1 for ten minutes and the app container never starts. What does this tell you?
Scenario
A hardened Pod spec sets runAsNonRoot: true at the container level and no runAsUser. The image's Dockerfile has no USER line. The Pod stays in CreateContainerConfigError. Which change fixes it with the smallest edit?
Scenario
Two containers in one Pod serve HTTP and one of them crashes with 'address already in use' on port 8080. Both listen on 8080. What is the correct fix?

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.

Further reading

On this page