Pods and Multi Container Patterns

Topics Covered

Pod Spec Essentials, Commands and Args

The fields you will use most

restartPolicy and what it means

Images and pull policy

command and args

The same distinction in kubectl run

Environment variables

Pods are mostly immutable

Ports and names

Reading a pod quickly

A worked fix: the container that exits immediately

Almost every task on both exams touches a pod spec, either directly or through the pod template inside a Deployment, Job or DaemonSet. The concepts are familiar from Codemia's Containers and Kubernetes course; this lesson is about writing and fixing pod specs quickly and correctly. It starts with the fields you will type most often and the one distinction that trips up more candidates than any other: command versus args.

The fields you will use most

A pod spec has dozens of fields, but a short list covers most tasks. At the pod level: containers, initContainers, volumes, restartPolicy, nodeSelector, tolerations, affinity, serviceAccountName, securityContext and terminationGracePeriodSeconds. At the container level: name, image, command, args, env, envFrom, ports, resources, volumeMounts, livenessProbe, readinessProbe, startupProbe, securityContext and imagePullPolicy.

A minimal but complete pod looks like this:

yaml
1apiVersion: v1
2kind: Pod
3metadata:
4  name: api
5  namespace: shop
6  labels:
7    app: api
8spec:
9  containers:
10  - name: api
11    image: nginx:1.27
12    ports:
13    - containerPort: 80

Generate the skeleton with kubectl run and dry run rather than typing it, as the previous lesson showed, and add fields from there. When you add a field, put it at the right level: probes, resources and volumeMounts belong to a container, while volumes, restartPolicy and nodeSelector belong to the pod. Indentation errors that put a container field at the pod level are a very common cause of rejected manifests.

restartPolicy and what it means

restartPolicy applies to all containers in the pod and has three values. Always restarts containers whenever they exit, which is what long running services want and the only value a Deployment allows. OnFailure restarts only on a non zero exit, which suits batch work. Never leaves exited containers stopped. kubectl run creates pods with Always by default; add --restart=Never for a one shot pod, which is handy for quick test commands like a DNS lookup or a curl against a Service.

bash
k -n shop run tmp-curl --image=curlimages/curl:8.10.1 --restart=Never --rm -it -- curl -s web-svc

The --rm and -it flags attach you to the pod and delete it when the command exits, which keeps the namespace clean.

Images and pull policy

The image field takes a repository, an optional registry prefix and a tag or digest. Always use the exact tag the task specifies. If you omit a tag, the image defaults to latest and imagePullPolicy defaults to Always; with any other tag, the default policy is IfNotPresent. A task that says an image must never be pulled from the registry if present on the node is asking for imagePullPolicy: IfNotPresent, and one that says always fetch the newest copy is asking for Always.

A pod stuck in ImagePullBackOff or ErrImagePull usually has a typo in the image name or tag, a private registry without credentials, or a registry the node cannot reach. kubectl describe pod shows the exact error in the events at the bottom.

command and args

Every container image defines what runs when it starts, using two settings in its build file: ENTRYPOINT, the executable, and CMD, the default arguments. In the pod spec, command overrides ENTRYPOINT and args overrides CMD. They are independent: setting only args keeps the image's entrypoint and replaces only its default arguments.

command overrides the image entrypoint and args overrides its default arguments.

That gives four cases worth knowing:

  • Neither set: the image runs as built.
  • Only args set: the image's entrypoint runs with your arguments.
  • Only command set: your command runs and the image's CMD is ignored.
  • Both set: your command runs with your arguments.

Both fields are lists of strings. A shell command with pipes or variables needs a shell to interpret it, so the usual pattern is to run sh with -c and pass the whole script as one string:

yaml
    command: ["sh", "-c"]
    args: ["while true; do date >> /data/out.log; sleep 5; done"]

or equivalently, everything in command:

yaml
1    command:
2    - sh
3    - -c
4    - while true; do date >> /data/out.log; sleep 5; done

The same distinction in kubectl run

kubectl run maps directly onto these fields. Words after a double dash become args. Adding --command before the double dash makes them command instead:

bash
k run a --image=busybox:1.36 $do -- sleep 3600
k run b --image=busybox:1.36 $do --command -- sleep 3600

For busybox, both work, because busybox's default is a shell and sleep 3600 as arguments is run as a command. For an image like nginx, whose entrypoint is a script that starts nginx, passing args changes what that script receives, while --command replaces it entirely. When a task says the container must run a specific command, use --command or set command in YAML; the grader may check the command field specifically.

Environment variables

Environment variables come from three places: literal values, references to ConfigMaps and Secrets, and references to the pod's own fields through the downward API. ConfigMaps and Secrets are covered in their own lesson. The downward API is worth knowing here because tasks sometimes ask a container to know its own pod name, namespace or node:

yaml
1    env:
2    - name: MODE
3      value: prod
4    - name: POD_NAME
5      valueFrom:
6        fieldRef:
7          fieldPath: metadata.name
8    - name: NODE_NAME
9      valueFrom:
10        fieldRef:
11          fieldPath: spec.nodeName

kubectl run --env=MODE=prod sets a literal value; the fieldRef form needs YAML. Verify environment variables with kubectl exec pod -- env, which prints what the process actually sees.

Pods are mostly immutable

Once a pod exists, most of its spec cannot change. You can update container images, add tolerations and adjust a few timing fields, but changing commands, adding volumes, probes or containers requires recreating the pod. The previous lesson showed the fast path: export the pod, edit the file and run replace --force. If the pod belongs to a Deployment, change the Deployment's template instead; editing a managed pod is pointless because the controller replaces it with one built from the template.

Recent Kubernetes versions also allow resizing a running pod's CPU and memory requests and limits in place through a dedicated resize subresource. Treat this as an advanced feature: for exam tasks that change resources, editing the owning Deployment or recreating the pod remains the expected path unless the task asks for an in place resize.

Ports and names

The ports list on a container is mostly informational: a container can listen on a port that is not declared, and traffic still reaches it. Declaring ports is still worth doing, for two reasons. Named ports let probes and Services refer to a port by name, so changing the number in one place updates every reference. And tasks often check that a container port is declared, so leaving it out costs a check even if the application works.

yaml
1    ports:
2    - name: http
3      containerPort: 8080
4      protocol: TCP

A Service can then target the name with targetPort: http, and a probe can use port: http. Names must be lowercase, at most fifteen characters, and unique within the pod.

Reading a pod quickly

When a task hands you an existing pod, you need to understand it fast. Three commands give you almost everything. describe shows the containers, images, commands, mounts, probes, conditions and recent events in one readable page. get with -o yaml shows the exact spec, which is what you edit. And logs shows what the process printed. A useful order is describe first, because the events at the bottom often explain a problem before you read anything else.

bash
k -n shop describe pod api | less
k -n shop get pod api -o yaml | less
k -n shop logs api --tail=50

A worked fix: the container that exits immediately

A common practice scenario is a pod in CrashLoopBackOff whose logs are empty. Describe shows the container terminated with exit code 0 a moment after starting, over and over. The cause is usually command and args: the container runs a command that finishes instantly, such as an echo, and with restartPolicy Always the kubelet restarts it, backing off longer each time. The fix is to give the container a long running process, for example sleep 3600 for a utility container, or to correct a command that was meant to start a server. Exit code 0 with CrashLoopBackOff almost always means a process that finished rather than one that failed.

args alone keeps the entrypoint

Setting only args replaces the image's default arguments but still runs its entrypoint. If a task says the container must run a specific command, set command, or use kubectl run with --command before the double dash.