Skip to content
LF Cert Trainer

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

1/9Multi-container Pods
0:00 / 3:17

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 livesWhat you getWhat it costs
Inside the application imageOne container, simple to runTwo teams release one image; a helper upgrade means rebuilding every app; a helper crash can take the app down
In its own PodIndependent scaling and releasesIt may land on another node: no shared files, no localhost, and nothing ties their lifetimes together
In a second container of the same PodSeparate images and releases, yet same node, same network, shared files, same lifetimeThe 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

Two containers in one PodPod web: one IP, one nodelocalhostwritesreadsContainer applistens on :8080Container agentreads logs, metricsVolume logsemptyDir
Two containers in one Pod. The containers talk over localhost and exchange files through a volume that both mount. Everything else (image, filesystem, command, limits) stays separate.

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 on localhost: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.volumes and mounted by each container that needs it, each at the path it likes, read-write or read-only. An emptyDir is 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 containersSeparate per container
IP address, port space, localhostImage and root filesystem
Hostname (the Pod's name)command, args, env
Volumes, where each container mounts themVolume mount paths and read-only flags
Node, service account, Pod restartPolicyCPU 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

The order containers start and stop inthenthenPod deletedthenInit containersrun one by one, exitSidecarsstart, keep runningApp containersstart in list orderApps stop firstall at the same timeSidecars stop lastin reverse order
The order containers start and stop in. Init containers come first, one at a time. Sidecars start next and keep running. App containers start last and are stopped first.

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:

  1. 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.
  2. 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.
  3. 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: if agent needs app to 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 emptyDir volumes 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

One container down, the whole Pod is not readyPod webremovedContainer apprunning, readyContainer agentCrashLoopBackOffREADY 1/2Pod is not ReadyService websends no traffic
One container down, the whole Pod is not ready. A Pod is Ready only when every container is ready. One crashing helper takes the Pod out of its Service, even if the main container works.

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:

ContainerCPU requestMemory request
app500m256Mi
agent100m64Mi
What the scheduler looks for on one node600m320Mi

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

KindWhere it is writtenRunsTypical use
App containerspec.containersFor the life of the Pod, next to the othersThe application, or a helper when order does not matter
Init containerspec.initContainersTo completion, before the app containersWait for a dependency, fetch or generate files
Sidecarspec.initContainers with restartPolicy: AlwaysStarts before the app containers, stops after themLog shipper, proxy, anything a Job must not wait for
Ephemeral containerAdded with kubectl debugOnce, in a running Pod, never restartedDebugging 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 seeLikely cause
1/2, CrashLoopBackOff, exit code 0The helper's command finishes; it needs a long-running command
1/2, CrashLoopBackOff, address already in use in the logsBoth containers listen on the same port
1/2, Running, no restartsA readiness probe fails in one container
No such file or directory in the helperThe volume is not mounted in both containers, or the paths differ
Init:0/1An 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 reaches 2/2.
  • Forgetting -c and reading the logs of the wrong container, then concluding that nothing is wrong.
  • Trying to add a container to a running Pod. kubectl edit pod rejects it. Edit the Deployment's template, or export the Pod, change it and run kubectl 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 Ready only 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, check READY 2/2, and use -c with logs and exec.

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.