Lesson 53 · Section 5: Application Lifecycle Management
Lesson 53: Multi-container Pods: several containers, one unit
Why you would put more than one container in a Pod, what the containers share and what they keep apart, how they start, restart and stop, and the commands that create and debug such Pods fast in the exam. · 22 min read · 3 min video
Official competencies this lesson covers
Narrated by the local narrator voice. Keys: Space plays and pauses, J and L step, C captions, F full screen.
Why put more than one container in a Pod
A container image should do one job. Yet an application rarely works alone: something has to ship its log files, expose its metrics in the format the monitoring system reads, refresh its configuration, or encrypt its traffic. There are three places to put such a helper:
| Where the helper lives | What you get | What it costs |
|---|---|---|
| Inside the application image | One container, simple to run | Two teams release one image; a helper upgrade means rebuilding every app; a helper crash can take the app down |
| In its own Pod | Independent scaling and releases | It may land on another node: no shared files, no localhost, and nothing ties their lifetimes together |
| In a second container of the same Pod | Separate images and releases, yet same node, same network, shared files, same lifetime | The two always scale together, and the Pod is only ready when both are |
The third option is a multi-container Pod. It exists for helpers that are useless without their application and that need to be physically next to it.
A web server and its database fail that test (you scale them differently), so they are separate Pods joined by a Service. A web server and the agent that tails its log files pass it.
What the containers share
Parts:
- Container app (listens on :8080), in Pod web: one IP, one node
- Container agent (reads logs, metrics), in Pod web: one IP, one node
- Volume logs (emptyDir), in Pod web: one IP, one node
Connections:
- Container agent and Container app: localhost
- Container app to Volume logs: writes
- Container agent to Volume logs: reads
A Pod is a set of Linux namespaces that all its containers join, plus a list of volumes. That gives containers in one Pod exactly two ways to work together:
- The network. There is one network namespace, so one IP address, one set of ports and one
localhost. The agent calls the application onlocalhost:8080; no Service and no DNS are involved. The other side of that coin: two containers cannot listen on the same port. - Volumes. A volume is declared once under
spec.volumesand mounted by each container that needs it, each at the path it likes, read-write or read-only. AnemptyDiris the usual choice: it is created empty when the Pod lands on the node, survives container restarts, and is deleted with the Pod.
Everything else stays separate:
| Shared by the Pod's containers | Separate per container |
|---|---|
IP address, port space, localhost | Image and root filesystem |
| Hostname (the Pod's name) | command, args, env |
| Volumes, where each container mounts them | Volume mount paths and read-only flags |
Node, service account, Pod restartPolicy | CPU and memory requests and limits |
| Inter-process communication (shared memory) | Probes, restart count, logs, security context |
Under the hood · Seeing each other's processes
Processes are not shared either: each container has its own process list, and its main process is PID 1. Setting
spec.shareProcessNamespace: true puts all containers of the Pod in one process namespace. Then ps in one
container lists the processes of all, a helper can send a signal to the application (for example SIGHUP to make
it reload its configuration), and the filesystem of another container can be reached through /proc/<pid>/root.
PID 1 becomes the hidden pause container, which matters for the few programs that insist on being PID 1.
How it works
In the manifest
spec.containers is a list. A multi-container Pod is simply a Pod with more than one entry:
apiVersion: v1
kind: Pod
metadata:
name: web
spec:
volumes:
- name: logs
emptyDir: {}
containers:
- name: app
image: nginx:1.29
volumeMounts:
- name: logs
mountPath: /var/log/nginx
- name: agent
image: busybox:1.37
command: ["sh", "-c", "tail -F /logs/access.log"]
volumeMounts:
- name: logs
mountPath: /logs
readOnly: true
Container names must be unique inside the Pod (init containers included), and you will need them for almost every
command later. The first container in the list is the default one for kubectl logs and kubectl exec.
Starting, restarting and stopping
Parts:
- Init containers (run one by one, exit)
- Sidecars (start, keep running)
- App containers (start in list order)
- Apps stop first (all at the same time)
- Sidecars stop last (in reverse order)
Connections:
- Init containers to Sidecars: then
- Sidecars to App containers: then
- App containers to Apps stop first: Pod deleted
- Apps stop first to Sidecars stop last: then
The kubelet starts the containers of a Pod in three groups:
- Init containers (
spec.initContainers) run one after another, and each must exit successfully before the next one starts. They prepare things, then they are gone. - Sidecars are init containers with
restartPolicy: Always. They start in their place in the init list, but the kubelet does not wait for them to exit: once a sidecar has started, the next container goes ahead, and the sidecar keeps running for the life of the Pod. - App containers (
spec.containers) are started in list order, without waiting for the previous one to be ready. Treat them as starting at the same time: ifagentneedsappto answer first, it has to retry.
On deletion the order is the reverse: all app containers get the stop signal at once, and sidecars are stopped only after the last app container has finished, in reverse order.
While the Pod runs, each container is supervised on its own:
- A container that exits is restarted alone, according to the Pod's
restartPolicy. The other containers keep running and are not told. - Each container has its own probes. A failing liveness probe restarts only that container.
- Each container has its own memory limit. Going over it gets that container
OOMKilled, not its neighbours. - The Pod's IP and its
emptyDirvolumes survive all of this, because they belong to the Pod.
Under the hood · Why sidecars became a kind of init container
For years the only way to run a helper was a second entry in spec.containers. That has two flaws. There is no
start order, so an application could start before the proxy it depends on. And nothing tells the helper to stop
when the main work is done: a Job whose main container finishes stays Running forever, because the log agent
next to it never exits.
Kubernetes solved both by letting an init container say restartPolicy: Always (on by default since v1.29, stable
since v1.33). Such a sidecar starts before the app containers, is restarted if it dies, does not keep a Job from
completing, and is stopped after the app containers. A plain second container in spec.containers is still valid
and still common; use it when neither order nor completion matters. The patterns built on helpers (sidecar,
adapter, ambassador) and init containers each get their own lesson next.
Ready means all of them
Parts:
- Container app (running, ready), in Pod web
- Container agent (CrashLoopBackOff), in Pod web
- READY 1/2 (Pod is not Ready)
- Service web (sends no traffic)
Connections:
- Container app to READY 1/2
- Container agent to READY 1/2
- READY 1/2 to Service web: removed
In kubectl get pods, READY 1/2 means one of two containers is ready. The Pod's own Ready condition is true
only when every container is ready, and only a ready Pod receives traffic from a Service. A crashing log agent
therefore takes a perfectly healthy web server out of rotation.
The STATUS column shows the worst container reason, so CrashLoopBackOff with 1/2 tells you one container is
fine and one is not. Which one is in kubectl describe pod, where every container has its own State,
Last State, Ready and Restart Count.
What the Pod as a whole asks from the node is the sum of its containers:
| Container | CPU request | Memory request |
|---|---|---|
app | 500m | 256Mi |
agent | 100m | 64Mi |
| What the scheduler looks for on one node | 600m | 320Mi |
A Pod stuck in Pending with Insufficient cpu may fit once you count what the helper asks for. Limits are
enforced per container.
Kinds of containers in a Pod
| Kind | Where it is written | Runs | Typical use |
|---|---|---|---|
| App container | spec.containers | For the life of the Pod, next to the others | The application, or a helper when order does not matter |
| Init container | spec.initContainers | To completion, before the app containers | Wait for a dependency, fetch or generate files |
| Sidecar | spec.initContainers with restartPolicy: Always | Starts before the app containers, stops after them | Log shipper, proxy, anything a Job must not wait for |
| Ephemeral container | Added with kubectl debug | Once, in a running Pod, never restarted | Debugging an image that has no shell |
Using it
Example · Create a Pod with two containers
Task: create a Pod web with a container app (image nginx:1.29) and a container agent (image
busybox:1.37) that runs sleep 3600.
kubectl run writes only one container, so let it write the skeleton and add the second by hand:
kubectl run web --image=nginx:1.29 --dry-run=client -o yaml > web.yaml
vi web.yaml
spec:
containers:
- name: app # was "web": rename it if the task names the container
image: nginx:1.29
- name: agent # the added block
image: busybox:1.37
command: ["sleep", "3600"]
kubectl apply -f web.yaml
kubectl get pod web # READY must say 2/2
busybox exits at once without a long-running command, and the Pod would show 1/2 and CrashLoopBackOff. That is
why the task gives it something to do.
Example · Add a log container to an existing Deployment
Task: the Deployment shop writes to /var/log/shop/app.log inside its container shop. Add a container
logger (image busybox:1.37) that prints that file to its standard output, so kubectl logs can read it.
The file lives in the first container's own filesystem, so the change has three parts: a volume, a mount in the existing container, and the new container with the same volume.
kubectl edit deployment shop
spec:
template:
spec:
volumes:
- name: logs # 1. a volume for the Pod
emptyDir: {}
containers:
- name: shop
image: registry.example.com/shop:2.4
volumeMounts:
- name: logs # 2. the app now writes into the volume
mountPath: /var/log/shop
- name: logger # 3. the new container reads from it
image: busybox:1.37
command: ["sh", "-c", "tail -n+1 -F /var/log/shop/app.log"]
volumeMounts:
- name: logs
mountPath: /var/log/shop
kubectl rollout status deployment shop
kubectl get pods -l app=shop # every Pod 2/2
kubectl logs deploy/shop -c logger # the application's log lines
tail -F (capital F) keeps retrying until the file exists, which covers the case where logger starts before
shop has written anything. Editing the template starts a rollout: the Pods are replaced, not changed.
Example · Find the broken container
A Pod shows 1/2 and you do not know why.
kubectl get pod web # READY 1/2, STATUS, RESTARTS
kubectl describe pod web # one block per container: State, Last State, Ready
kubectl get pod web -o jsonpath='{range .status.containerStatuses[*]}{.name}{"\t"}{.ready}{"\t"}{.restartCount}{"\n"}{end}'
kubectl logs web -c agent --previous # output of the run that crashed
kubectl exec -it web -c app -- sh # look around from the healthy container
| What you see | Likely cause |
|---|---|
1/2, CrashLoopBackOff, exit code 0 | The helper's command finishes; it needs a long-running command |
1/2, CrashLoopBackOff, address already in use in the logs | Both containers listen on the same port |
1/2, Running, no restarts | A readiness probe fails in one container |
No such file or directory in the helper | The volume is not mounted in both containers, or the paths differ |
Init:0/1 | An init container has not finished; read it with kubectl logs web -c <init name> |
Example · Check that two containers really share the network
kubectl exec web -c agent -- wget -qO- http://localhost:80 # answered by nginx in the other container
kubectl exec web -c agent -- hostname # "web": the same hostname in both
kubectl exec web -c agent -- ls /logs # files written by the other container
The request goes to localhost, yet a different container answers. That is the shared network namespace at work.
Tricks
Common mistakes
- Putting replicas in a Pod. Three copies of the same server in one Pod fight over the port and cannot be scaled. Replicas are Pods, made by a Deployment.
- Mounting the volume in only one container, or at paths that do not match what the command reads.
- A helper that exits. With
restartPolicy: Always, a container whose command finishes is restarted for ever and the Pod never reaches2/2. - Forgetting
-cand reading the logs of the wrong container, then concluding that nothing is wrong. - Trying to add a container to a running Pod.
kubectl edit podrejects it. Edit the Deployment's template, or export the Pod, change it and runkubectl replace --force -f. - Expecting a start order between app containers. There is none you can rely on; use an init container or a sidecar when order matters.
- Counting only the main container's requests when working out why a Pod does not fit on a node.
Recap
- A multi-container Pod is for helpers that cannot work apart from their application: same node, same lifetime, scaled together.
- The containers share the network (
localhost, one port space) and the volumes they mount; images, filesystems, commands and limits stay separate. - Each container is restarted on its own, but the Pod is
Readyonly when all containers are, and it requests the sum of their resources. - Order: init containers, then sidecars, then app containers; on shutdown, app containers first.
- In the exam: generate with
--dry-run=client -o yaml, add the second container by hand, checkREADY 2/2, and use-cwithlogsandexec.
Official docs
Quiz: check what you learned
5 questions on this lesson · about 3 min · instant feedback. Missed questions come back in your review queue.
Sign in to take the quiz and keep your score.
Practise: try it on a real cluster
2 hands-on labs for this lesson. You get goals, not steps: any solution that reaches them passes.
Add a sidecar and a shared volume to a running app so that its log file shows up in kubectl logs.
Build · Level 2 · standard · target 15 min
Get answers out of two pods that listen only on their own loopback address, one of them built from an image without a shell, with kubectl debug, port-forward and exec.
Investigate · Level 2 · standard · target 20 min
Discussion
Learners ask and answer questions here. Sign in to read and join the discussion.