TExcelTAD
Home › Kubernetes › Init & Sidecar Containers

Init & Sidecar Containers

Most Pods have a single application container. Sometimes, though, a helper must run next to or before the app, sharing its network and files. Kubernetes supports three patterns:

Kind Where Runs Typical use
Init container spec.initContainers To completion, one after another, before the app starts Wait for a database, run migrations, download config
Sidecar container spec.initContainers with restartPolicy: Always Starts before the app and keeps running alongside it Log shipper, proxy (service mesh), config reloader
Regular containers spec.containers In parallel, for the Pod's lifetime The application itself

Native sidecars (an init container with restartPolicy: Always) became stable in Kubernetes 1.33. Before that, people put helpers in spec.containers, which had no start-up ordering and kept Jobs from finishing.

Init containers

yaml
apiVersion: v1
kind: Pod
metadata:
  name: api
spec:
  initContainers:
    - name: wait-for-db
      image: busybox:1.37
      command: ["sh", "-c", "until nc -z db 5432; do echo waiting; sleep 2; done"]
    - name: migrate
      image: ghcr.io/acme/api:2.3.1
      command: ["./manage", "migrate"]
  containers:
    - name: api
      image: ghcr.io/acme/api:2.3.1

Rules worth memorising:

  • Init containers run sequentially, in the listed order. Each must exit with code 0 before the next starts.
  • If one fails, the kubelet restarts it (subject to the Pod's restartPolicy) and the app containers never start. The Pod shows Init:0/2, Init:Error or Init:CrashLoopBackOff.
  • Init containers support no readiness probes, because they must finish.

This model plays the start-up sequence of a Pod. migrate fails twice before succeeding:

python · try it yourself
def start_pod(init_containers, app_containers):
    events = []
    for name, attempts in init_containers:
        for attempt, ok in enumerate(attempts, start=1):
            events.append(f"init {name} attempt {attempt}: {'exit 0' if ok else 'exit 1'}")
            if ok:
                break
        else:
            events.append(f"Pod stuck in Init:CrashLoopBackOff ({name})")
            return events
    for name in app_containers:
        events.append(f"start app container {name}")
    return events

for line in start_pod([("wait-for-db", [True]), ("migrate", [False, False, True])], ["api"]):
    print(line)
print("---")
for line in start_pod([("wait-for-db", [False, False, False])], ["api"]):
    print(line)
init wait-for-db attempt 1: exit 0
init migrate attempt 1: exit 1
init migrate attempt 2: exit 1
init migrate attempt 3: exit 0
start app container api
---
init wait-for-db attempt 1: exit 1
init wait-for-db attempt 2: exit 1
init wait-for-db attempt 3: exit 1
Pod stuck in Init:CrashLoopBackOff (wait-for-db)

Sidecars and shared volumes

A sidecar typically shares an emptyDir volume with the app. Here a log shipper tails the file that nginx writes:

yaml
apiVersion: v1
kind: Pod
metadata:
  name: web-with-logs
spec:
  volumes:
    - name: logs
      emptyDir: {}
  initContainers:
    - name: log-shipper
      image: busybox:1.37
      restartPolicy: Always            # this makes it a native sidecar
      command: ["sh", "-c", "tail -F /var/log/nginx/access.log"]
      volumeMounts:
        - {name: logs, mountPath: /var/log/nginx}
  containers:
    - name: nginx
      image: nginx:1.27
      volumeMounts:
        - {name: logs, mountPath: /var/log/nginx}
bash
kubectl logs web-with-logs -c log-shipper -f     # -c picks the container
kubectl exec -it web-with-logs -c nginx -- sh

Order matters at shutdown too: native sidecars start before and stop after the main containers, so the log shipper still catches the last lines.

python · try it yourself
def lifecycle(inits, sidecars, apps):
    order = []
    for c in inits:
        order.append(f"run init {c} to completion")
    for c in sidecars:
        order.append(f"start sidecar {c}")
    for c in apps:
        order.append(f"start app {c}")
    order.append("... Pod is running ...")
    for c in reversed(apps):
        order.append(f"stop app {c}")
    for c in reversed(sidecars):
        order.append(f"stop sidecar {c}")
    return order

print("\n".join(lifecycle(["fetch-config"], ["log-shipper", "proxy"], ["nginx"])))
run init fetch-config to completion
start sidecar log-shipper
start sidecar proxy
start app nginx
... Pod is running ...
stop app nginx
stop sidecar proxy
stop sidecar log-shipper

Other multi-container patterns

  • Ambassador: a proxy container that the app talks to on localhost, which forwards to an external service (e.g. a database proxy handling TLS and credentials).
  • Adapter: converts the app's output into a standard format, such as exposing legacy metrics as Prometheus metrics.

Tip: Only put containers in one Pod if they must share a lifecycle and resources. If two parts can scale independently (web front end and API), they belong in separate Deployments.

Test yourself

How do init containers run?

  1. In parallel with the app
  2. One after another, each to completion, before the app starts
  3. Only when the app crashes
  4. After the Pod is deleted

What turns an init container into a native sidecar?

  1. sidecar: true
  2. restartPolicy: Always on the init container
  3. Putting it last in containers
  4. A special image

Which kubectl flag selects a specific container in a multi-container Pod?

  1. -n
  2. -c
  3. -l
  4. -o