Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 78 ยท Pods

Init Containers and Sidecars

Use init containers for setup work, native sidecar containers for long-running helpers, and the ambassador and adapter patterns, with start and stop ordering.

Real applications rarely start from nothing. A web service may need its database schema migrated before the first request, a config file downloaded before the server reads it, or a certificate fetched before it can speak TLS. Others need a permanent helper next to them: something that ships logs, refreshes credentials or proxies outgoing calls. Kubernetes has a place for each. Init containers do work that must finish before the application starts. Sidecar containers run beside the application for as long as it runs.

Both live inside the same Pod, so they share its network and volumes (Pods). What differs is the order in which Kubernetes starts and stops them. This lesson covers init containers, the native sidecar feature, the classic ambassador and adapter patterns, and the exact start and stop order. A Python stand-in simulates that order from a manifest-like description, so you can predict what happens before you ever apply one.

Manifests are read-only. The Python programs reproduce the ordering rules and are not the kubelet.

Helpers around the main container

Init container Runs once, to completion, before anything else.
Sidecar Runs alongside the app for its whole life.
Main container Your actual application.
1 / 2

Init containers

Init containers are listed under spec.initContainers. They run one at a time, in order, and each must exit with code 0 before the next starts. Only when all of them have succeeded do the regular containers start. If one fails, the kubelet retries it according to restartPolicy, and the Pod stays in Init: status (for example Init:0/2 or Init:CrashLoopBackOff).

YAML
apiVersion: v1
kind: Pod
metadata:
  name: web
spec:
  volumes:
    - name: config
      emptyDir: {}
  initContainers:
    - name: wait-for-db
      image: busybox:1.37
      command: ["sh", "-c", "until nc -z db 5432; do echo waiting; sleep 2; done"]
    - name: fetch-config
      image: busybox:1.37
      command: ["sh", "-c", "echo 'mode=production' > /cfg/app.conf"]
      volumeMounts:
        - name: config
          mountPath: /cfg
  containers:
    - name: web
      image: example/web:2.0
      volumeMounts:
        - name: config
          mountPath: /etc/app

This shows the three common reasons for init containers:

  • Waiting for something. A dependency such as a database must be reachable first. (Prefer apps that retry on their own, but waiting is a fine fallback.)
  • Preparing shared files. The init container writes into a volume that the main container later reads. Here fetch-config creates app.conf.
  • One-off setup with different tools. Init containers can use a different image from the app, so the app image stays small. Tools like git, curl or a migration runner need not be inside it.

Other facts worth remembering: readiness and liveness probes do not apply to classic init containers, since they just run to completion. They do support resources, and they run again whenever the Pod sandbox is recreated (for example after a node restart or when a replacement Pod is created), and after failures they are retried, so they must be idempotent: safe to run twice. Restarting a single main container does not re-run them.

Init containers and resource requests

The scheduler needs a single number for the Pod. For classic init containers it takes the larger of two values: the biggest init container request, or the sum of all app container requests. The reason is that init containers run one after another and never at the same time as the app. A one-off heavy migration step does not need to be added to the steady-state total, but it still must fit.

The problem with long-running helpers

Before native sidecars existed, a helper was just another entry in containers. That caused two awkward problems:

  1. No start order. All regular containers start together. If the app needs a proxy ready first, you had to build retry logic or sleep loops.
  2. Jobs never finished. A Job's Pod ends only when all containers exit. A log-shipping helper that runs forever kept the Job alive, so people wrote hacks to kill it.

Native sidecar containers

Current Kubernetes versions solve both with a small trick: a sidecar is an init container with restartPolicy: Always. It is declared in initContainers, so it starts in order, but because of the restart policy the kubelet does not wait for it to finish. It starts, counts as started once its startup probe (if any) passes, and the next container proceeds while the sidecar keeps running.

YAML
apiVersion: v1
kind: Pod
metadata:
  name: app-with-logger
spec:
  volumes:
    - name: logs
      emptyDir: {}
  initContainers:
    - name: log-shipper
      image: example/log-shipper:3.1
      restartPolicy: Always          # makes it a sidecar
      volumeMounts:
        - name: logs
          mountPath: /var/log/app
          readOnly: true
  containers:
    - name: app
      image: example/app:1.0
      volumeMounts:
        - name: logs
          mountPath: /var/log/app

What changes compared with a plain container:

  • Start order is guaranteed. The sidecar starts before the app and before any later init containers.
  • Restarts are independent. If the sidecar crashes, only it restarts, even when the Pod's own restartPolicy is Never.
  • Shutdown order is reversed. When the Pod ends, the main containers stop first, and then the sidecars stop, in reverse order of how they were declared. A log shipper therefore stays alive to catch the app's last lines.
  • Jobs can finish. Once all main containers exit, the Pod completes even if a sidecar is still running, because the kubelet stops the sidecars.
  • Probes work. A sidecar can have a startup, readiness and liveness probe. Its readiness counts toward the Pod being Ready.

This feature is stable in Kubernetes 1.33 and later. On older clusters, it was behind a feature gate, and the older "just add another container" approach was the only portable option.

Three well-known patterns

Sidecars are used in a few recurring roles, and the names are worth knowing because documentation and interviews use them.

Sidecar (helper). Adds a supporting capability next to the app: shipping logs from a shared volume, syncing content from git, renewing credentials, running a service mesh proxy. The app does not know the helper exists.

Ambassador. A proxy that represents the outside world to the app. The app talks to localhost:6379, and the ambassador handles the details of reaching the real service: choosing a shard, adding TLS, retrying. It keeps connection logic out of the application code.

Adapter. Converts the app's output into a standard format. For example, an app exposes statistics in a custom text format and the adapter publishes them as Prometheus metrics on a known port. The monitoring system sees one shape regardless of the app.

TEXT
            +--------------------- Pod ----------------------+
 requests ->|  [ambassador] <-localhost-> [app] -> /logs vol  |
            |                              ^                  |
            |                       [adapter] -> :9100        |
            +-------------------------------------------------+

All three rely on exactly the things a Pod shares: localhost and volumes. They also come with a cost, though. Each sidecar adds CPU and memory to every replica, adds another thing that can fail and makes the Pod slower to start. Use one when the benefit is real, for example when you cannot change the application, not just because it is possible.

Predicting the order

This stand-in reads a Pod description and prints the timeline. It implements the rules from above: init containers run one by one, sidecars start and stay running, main containers start together, and shutdown runs main containers first and sidecars in reverse. Durations are made up, so you can see how the clock advances.

Python Ordered startup of a Pod

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The first Pod shows declaration order mattering. mesh-proxy is a sidecar listed before fetch-config, so it is already running while the later init container does its work. The second Pod shows a failing init container blocking everything after it.

Working out the scheduling request

A second small stand-in computes the Pod's effective CPU request with the rule from earlier. Sidecars add to the long-running total because they stay alive next to the app, while classic init containers only matter if one of them is bigger than that total.

Python Effective request of a Pod

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

With the heavy 1000m migration the scheduler reserves 1000m, even though the app only uses 600m in steady state. This is the right trade-off: a Pod that can start must also fit during its start. If a migration is that heavy, consider running it as a separate Job (Jobs and CronJobs) so that every replica does not reserve it.

When not to use these

Init containers are a poor place for long, risky work such as database migrations in a multi-replica Deployment, because every replica runs them. Running migrations from a Job, or from a Helm hook (Helm: Charts and Releases), keeps them single and visible. Sidecars are a poor place for logic that could be a library or a node-level agent: a logging DaemonSet (DaemonSets) serves a whole node instead of adding a copy to every Pod.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How do classic init containers run?

    Init containers run sequentially to completion. The regular containers start only after every init container has succeeded.
  2. 2. How do you declare a native sidecar container?

    A native sidecar is an init container with restartPolicy Always. It starts in order but keeps running while later containers start.
  3. 3. What is the shutdown order for native sidecars?

    Sidecars outlive the main containers so they can handle last logs or traffic, and they stop in reverse order.
  4. 4. Which pattern describes a proxy that handles how the app reaches an external service, so the app just calls localhost?

    The ambassador represents the outside service to the app and handles sharding, TLS and retries. An adapter instead converts the app's output format.
  5. 5. Why must init container work be idempotent?

    Failed init containers are retried, and a recreated Pod runs them again, so they must be safe to repeat.

Summary

  • Init containers run one after another to completion before the app starts, and are ideal for waiting, preparing shared files and one-off setup with other tools.
  • A native sidecar is an init container with restartPolicy: Always: it starts in order and keeps running beside the app.
  • Sidecars stop after the main containers, in reverse order, and no longer keep Jobs from finishing.
  • The ambassador (proxy for outgoing calls), adapter (format converter) and helper (logs, sync) patterns rely on shared localhost and volumes.
  • Every sidecar adds cost to each replica, so use them deliberately; the scheduler sizes the Pod from the app containers, sidecars and the biggest init step.

Next, learn how Kubernetes finds and groups Pods in Labels, Selectors and Annotations.