Skip to content
LF Cert Trainer

Lesson 54 · Section 5: Application Lifecycle Management

Lesson 54: Multi-container Pod design patterns: sidecar, adapter, ambassador

The three classic ways to put a helper container next to an application, how each one uses the Pod's shared network and volumes, how Kubernetes runs a real sidecar, and how to add one fast in the exam. · 20 min read · 4 min video

1/10Multi-container Pod design patterns
0:00 / 3:57

Narrated by the local narrator voice. Keys: Space plays and pauses, J and L step, C captions, F full screen.

Why design patterns for Pods

The previous lesson showed that a Pod can run several containers, and what they share: one IP address, one localhost, and any volume both of them mount. This lesson is about why you would use that, and the answer is almost always the same: to keep the application container small and focused, and to put everything around it into a separate, reusable helper.

Think about what a production application needs besides its own code: its logs must reach a central store, its metrics must be readable by the monitoring system, its outgoing connections may need encryption, retries or routing. You can build all of that into every application, in every programming language your teams use, and update every one of them when the log store changes. Or you build each concern once, as a small container image, and place that container next to any application that needs it.

Three shapes of that idea come back so often that they have names: sidecar, adapter and ambassador. They come from the paper "Design patterns for container-based distributed systems" by Brendan Burns and David Oppenheimer, two of the people behind Kubernetes.

The three patterns

Sidecar: add a feature next to the app

Sidecar: add a feature next to the appPod webwritesreadsshipsContainer appwrites app.logVolume logsemptyDirSidecar shippertails the fileLog storeoutside the Pod
Sidecar: add a feature next to the app. The application only writes a file. The sidecar reads the same volume and ships the lines away. The app does not know the sidecar exists.

Parts:

  • Container app (writes app.log), in Pod web
  • Volume logs (emptyDir), in Pod web
  • Sidecar shipper (tails the file), in Pod web
  • Log store (outside the Pod)

Connections:

  • Container app to Volume logs: writes
  • Sidecar shipper to Volume logs: reads
  • Sidecar shipper to Log store: ships

A sidecar extends or improves the main container without changing it. The application does its work and is not aware of the helper.

The standard example is logging. Many older applications write to a log file instead of standard output, so kubectl logs shows nothing. A sidecar that mounts the same volume can tail the file to its own standard output (now kubectl logs -c works and the node's log collector picks it up), or ship the lines straight to a log store.

Other sidecars you will meet:

  • a config reloader that watches a ConfigMap volume and tells the application to reload,
  • a content puller that keeps a directory in sync with a Git repository while nginx serves it,
  • a service mesh proxy (Envoy in Istio, the Linkerd proxy) that handles all traffic in and out of the Pod.

Adapter: one standard face for the outside

Adapter: one standard face for the outsidePod webPod cachescrapeasksscrapeasksPrometheusscrapes /metricsAdapter exporterserves :9113Container nginxstub_statusAdapter exporterserves :9121Container redisINFO command
Adapter: one standard face for the outside. Each application reports its status in its own format. An adapter in every Pod translates it, so the monitoring system reads all Pods the same way.

Parts:

  • Prometheus (scrapes /metrics)
  • Adapter exporter (serves :9113), in Pod web
  • Container nginx (stub_status), in Pod web
  • Adapter exporter (serves :9121), in Pod cache
  • Container redis (INFO command), in Pod cache

Connections:

  • Prometheus to Adapter exporter: scrape
  • Adapter exporter to Container nginx: asks
  • Prometheus to Adapter exporter: scrape
  • Adapter exporter to Container redis: asks

An adapter takes what the application produces and translates it into the format the rest of your platform expects. The outside world looks in, and the adapter makes every Pod look the same.

The standard example is monitoring. Prometheus wants every target to serve metrics as text on an HTTP endpoint. nginx reports its numbers on a stub_status page, Redis answers the INFO command, a Java application exposes JMX. An exporter container in each Pod asks its application over localhost, converts the answer and serves it in the Prometheus format. The same idea works for logs: an adapter rewrites the log lines of very different applications into one common format before they are collected.

Ambassador: a local door to the outside

Ambassador: a local door to the outsidePod shopcallsroutesroutesContainer appcalls localhost:6379Ambassador proxylistens on :6379redis-0shard 1redis-1shard 2
Ambassador: a local door to the outside. The application always calls localhost. The ambassador knows where the real service is, and handles routing, retries or encryption on the way out.

Parts:

  • Container app (calls localhost:6379), in Pod shop
  • Ambassador proxy (listens on :6379), in Pod shop
  • redis-0 (shard 1)
  • redis-1 (shard 2)

Connections:

  • Container app to Ambassador proxy: calls
  • Ambassador proxy to redis-0: routes
  • Ambassador proxy to redis-1: routes

An ambassador is a proxy for the application's outgoing connections. The application looks out, and always sees something simple: a server on localhost.

The application connects to localhost:6379 as if a single Redis were running beside it. The ambassador listens on that port and does the hard part: it finds the right shard, opens a TLS connection, retries, or sends the request to a different database in the test environment than in production. Real examples are the Cloud SQL Auth Proxy, which lets an application reach a managed database on localhost, and a kubectl proxy container that lets an application call the Kubernetes API on localhost:8001 without handling tokens and certificates.

Telling them apart

SidecarAdapterAmbassador
What it doesAdds a feature to the appTranslates the app's outputProxies the app's outgoing calls
DirectionBeside the appOutside looks inApp looks out
Talks to the app throughA shared volume or localhostlocalhost or a shared volumelocalhost
Typical exampleLog shipper, config reloaderPrometheus exporter, log formatterDatabase proxy, API proxy
The app knows about it?NoNoOnly as "a server on localhost"

The borders are soft. A service mesh proxy is a sidecar that also acts as an ambassador for outgoing traffic, and many people call every helper container "a sidecar". In the exam, the pattern name in a task tells you the purpose; the YAML you write is the same kind of thing every time: a second container plus a shared volume or a port.

How it works

Nothing in the Pod spec says "pattern". The patterns work because of two things every Pod gives its containers.

One network namespace. All containers in a Pod share the same IP address and port space. A helper reaches the application on localhost:<port>, with no Service, no DNS name and no network hop. This is what adapters and ambassadors use. The price is that two containers cannot listen on the same port.

Shared volumes. Each container has its own filesystem, so a file written by one is invisible to the other. A volume declared once in spec.volumes and mounted by both (usually an emptyDir, which lives as long as the Pod) gives them a common directory. This is what a logging sidecar uses. The mount paths may differ per container; the volume name is what links them.

  1. Pick the link: shared volume or localhost
  2. Declare the volume once in the Pod
  3. Mount it in both containers
  4. Add the helper container
  5. Check with logs -c and exec -c
Building any helper container

Two ways to write the helper

The classic way lists the helper under spec.containers, next to the application. Kubernetes treats all entries there as equals: it starts them in list order without waiting for one to be ready before starting the next, and stops them all at once. That is enough for many cases, and it is the only way on old clusters.

The native way lists the helper under spec.initContainers and gives that container restartPolicy: Always. Kubernetes calls this a sidecar container. The feature is on by default since Kubernetes 1.29 and stable since 1.33.

The life of a native sidecarthenthenPod deletedthenInit containerruns, then exitsSidecarstarts, keeps runningApp containerstarts lastApp containerstops firstSidecarstops last
The life of a native sidecar. A sidecar is an init container with restartPolicy Always. It starts before the application, keeps running beside it, and is stopped only after the application has stopped.

Parts:

  • Init container (runs, then exits)
  • Sidecar (starts, keeps running)
  • App container (starts last)
  • App container (stops first)
  • Sidecar (stops last)

Connections:

  • Init container to Sidecar: then
  • Sidecar to App container: then
  • App container to App container: Pod deleted
  • App container to Sidecar: then

That one field changes the container's life:

  • It starts before the application. Init containers start in list order. A regular init container must finish before the next one starts; a sidecar only has to be started (and pass its startupProbe, if it has one). The application containers start after all init containers have had their turn.
  • It keeps running. A regular init container runs to completion. A sidecar stays up for the whole life of the Pod and is restarted whenever it exits, even if the Pod's own restartPolicy is Never or OnFailure.
  • It stops last. When the Pod is deleted, the kubelet stops the application containers first, then the sidecars, in the reverse of their start order. A log shipper still gets the application's final lines, and a proxy is still there while the application closes its connections.
  • It does not block completion. In a Job, the Pod is finished when the application containers are done; the sidecar is then shut down. With a classic helper under containers, the Job would never complete, because the helper never exits.
  • It can have probes. Unlike regular init containers, a sidecar supports startupProbe, readinessProbe and livenessProbe, and its readiness counts for the Pod's readiness.
Classic (containers)Native sidecar (initContainers + restartPolicy: Always)
Start orderWith the app, no waitingBefore the app
Stop orderTogether with the appAfter the app
In a JobKeeps the Pod running foreverDoes not block completion
Restart ruleThe Pod's restartPolicyAlways
Counted in READYYesYes
Under the hood · What a sidecar costs

A helper is not free, and it is repeated in every replica.

  • Resources. The scheduler adds the requests of a sidecar to the requests of the application containers, because they run at the same time. (A regular init container is different: it runs alone, so only the largest one counts.) A proxy that asks for 100m CPU costs 5 CPUs across 50 replicas.
  • Readiness. The Pod is Ready only when every container is ready, sidecars included. A broken helper takes the Pod out of its Service, even when the application is fine. READY 1/2 usually points here.
  • Coupling. You cannot scale, update or restart the helper apart from the application. Changing the helper's image rolls out every Pod of the Deployment.

That is why cluster-wide concerns are often solved per node instead: one log collector per node in a DaemonSet reads the standard output of all containers, with no helper in any Pod. Use a helper container when the work truly belongs to one application: its own log files, its own metrics format, its own outgoing connections. A different application that the first one merely talks to, such as its database, belongs in its own Pod behind a Service.

Using it

Example · Sidecar: make a log file readable with kubectl logs

The application writes to /var/log/app/app.log, not to standard output. Add a native sidecar that streams the file.

apiVersion: v1
kind: Pod
metadata:
  name: web
spec:
  initContainers:
    - name: shipper
      image: busybox:1.37
      restartPolicy: Always
      command: ["sh", "-c", "tail -n+1 -F /var/log/app/app.log"]
      volumeMounts:
        - name: logs
          mountPath: /var/log/app
  containers:
    - name: app
      image: busybox:1.37
      command: ["sh", "-c", "while true; do echo \"$(date) request served\" >> /var/log/app/app.log; sleep 5; done"]
      volumeMounts:
        - name: logs
          mountPath: /var/log/app
  volumes:
    - name: logs
      emptyDir: {}
kubectl apply -f web.yaml
kubectl get pod web                      # READY 2/2: the sidecar counts
kubectl logs web -c shipper              # the lines the app wrote to the file
kubectl logs web -c app                  # empty: the app prints nothing itself

tail -F (capital F) keeps retrying until the file exists, which matters because the sidecar starts before the application creates it. -n+1 prints the file from its first line.

Example · Exam style: add a sidecar to an existing Deployment

The task: "Deployment legacy in namespace apps writes its log to /var/log/legacy/app.log. Add a co-located container sidecar with image busybox:1.37 that runs tail -n+1 -F /var/log/legacy/app.log, sharing the log directory through a volume."

kubectl -n apps edit deployment legacy

Add three things to the Pod template (spec.template.spec):

      containers:
        - name: legacy                 # the existing container
          image: registry.example.com/legacy:2.1
          volumeMounts:                # 1. mount the volume in the app
            - name: logs
              mountPath: /var/log/legacy
        - name: sidecar                # 2. the new container
          image: busybox:1.37
          command: ["sh", "-c", "tail -n+1 -F /var/log/legacy/app.log"]
          volumeMounts:
            - name: logs
              mountPath: /var/log/legacy
      volumes:                         # 3. the shared volume
        - name: logs
          emptyDir: {}
kubectl -n apps rollout status deployment legacy
kubectl -n apps logs deploy/legacy -c sidecar --tail=5

Saving the edit changes the Pod template, so the Deployment rolls out new Pods by itself. Listing the helper under containers answers "co-located container". If the task says "sidecar container that starts before the application" or names restartPolicy: Always, write the same container under initContainers with that field.

Example · Adapter: expose nginx status as Prometheus metrics

nginx can report its connection counts on a status page, but not in the Prometheus format. The exporter container reads the page over localhost and serves /metrics on port 9113.

apiVersion: v1
kind: ConfigMap
metadata:
  name: nginx-status
data:
  status.conf: |
    server {
      listen 8080;
      location /stub_status { stub_status; }
    }
---
apiVersion: v1
kind: Pod
metadata:
  name: web-metrics
spec:
  containers:
    - name: nginx
      image: nginx:1.29
      volumeMounts:
        - name: conf
          mountPath: /etc/nginx/conf.d/status.conf
          subPath: status.conf
    - name: exporter
      image: nginx/nginx-prometheus-exporter:1.4
      args: ["--nginx.scrape-uri=http://localhost:8080/stub_status"]
      ports:
        - containerPort: 9113
  volumes:
    - name: conf
      configMap:
        name: nginx-status
kubectl exec web-metrics -c nginx -- curl -s localhost:8080/stub_status   # nginx's own format
kubectl exec web-metrics -c nginx -- curl -s localhost:9113/metrics       # the adapter's translation

Both curl commands run in the nginx container, and the second one still reaches the exporter: port 9113 belongs to the Pod, not to one container.

Example · Ambassador: reach a remote database on localhost

The application is configured once, with localhost:6379. The ambassador forwards that port to wherever Redis really lives; here a socat container does it in one line.

apiVersion: v1
kind: Pod
metadata:
  name: shop
spec:
  containers:
    - name: app
      image: redis:8                   # stands in for an app; it brings redis-cli
      command: ["sleep", "infinity"]
    - name: ambassador
      image: alpine/socat:1.8.0.3
      args: ["TCP-LISTEN:6379,fork,reuseaddr", "TCP:redis.data.svc.cluster.local:6379"]
kubectl exec shop -c app -- redis-cli -h localhost ping     # PONG, answered by the remote Redis

To point the application at another Redis, change the ambassador's argument. The application's own configuration never changes, in any environment.

Tricks

Common mistakes

  • Mounting the volume in one container only. The volume is declared once, but each container that needs the files must have its own volumeMounts entry. Without it, the helper looks at its own empty filesystem.
  • Different volume names, same path. Two containers that each mount their own emptyDir at /var/log/app do not share anything. The volume name is what makes it one directory.
  • Putting restartPolicy: Always in the wrong place. Under spec it is the Pod's policy (and already the default). It makes a sidecar only on an entry of initContainers.
  • A helper in initContainers without restartPolicy: Always. A long-running command there never completes, so the application never starts and the Pod hangs in Init:0/1.
  • Two containers on one port. They share the port space. An ambassador on 6379 next to a local Redis on 6379 means one of them fails to bind and crash-loops.
  • A classic sidecar in a Job. The helper never exits, so the Pod never completes. Use a native sidecar.
  • Using tail -f on a file that does not exist yet. It exits at once and the helper restarts in a loop. tail -F waits for the file.
  • Putting separate applications in one Pod. A web application and its database scale and fail differently. They are two Pods and a Service, not a pattern.

Recap

  • Helper containers work because a Pod's containers share localhost and can share volumes.
  • Sidecar extends the app (log shipper), adapter standardises what the outside reads (metrics exporter), ambassador proxies what the app calls (database proxy). Kubernetes itself does not know these names.
  • A native sidecar is an entry in initContainers with restartPolicy: Always: it starts before the app, runs beside it, stops after it, and does not keep a Job from completing.
  • A helper under containers also works; it simply starts and stops together with the app.
  • In the exam: declare the volume once, mount it in both containers, 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

A hands-on lab for this lesson. You get goals, not steps: any solution that reaches them passes.

Discussion

Learners ask and answer questions here. Sign in to read and join the discussion.