HAMZA KAREEM / CONCEPTS hamzawi.dev

Lesson 1562 min read

Native Sidecars (initContainers restartPolicy: Always)

the initContainers field that fixes Jobs that never finish

Cloud infrastructurecloud infrastructure / Kubernetes

Two ways to run a sidecar

Old way: add a second entry to spec.containers. App and proxy run as peers.

New way (k8s 1.29+): put it in spec.initContainers with restartPolicy: Always. Kubernetes calls that a sidecar container.

Same image, same job — a completely different lifecycle.

Three bugs the old way hands you

  • Jobs never complete. A Job is done when every containers entry exits. Your Envoy or Fluent Bit sidecar never exits, so the Job sits in Running forever and the CronJob piles up unfinished runs.
  • Startup race. Entries in containers start in parallel. The app's first outbound call fires before the proxy is listening — connection refused for the first second or two of every cold pod.
  • Shutdown race. SIGTERM goes to everything at once. If the proxy dies first, the app's in-flight requests fail during drain.

The fix is one field

spec:
  initContainers:
    - name: envoy
      image: envoyproxy/envoy:v1.31
      restartPolicy: Always      # <- this makes it a sidecar
      startupProbe:
        httpGet: { path: /ready, port: 15021 }
  containers:
    - name: app
      image: myapp:1.4

What the lifecycle change buys you

  • Starts before containers and must pass its startup probe first, so no startup race
  • Stays running for the pod's whole life and is restarted if it crashes, unlike a plain init container
  • Does not block Job completion — the Job ends when app exits
  • Terminates after the main containers, in reverse order, so you get a clean drain

The gotchas

  • restartPolicy: Always is legal only on an initContainers entry, and Always is the only value allowed there. In spec.containers it is a validation error.
  • Resource math changes. Plain init container requests are max()'d against the app's; sidecar requests are added to the pod's effective requests. Move a 500m / 512Mi proxy into initContainers and the scheduler suddenly needs 500m more per pod — pods that used to fit go Pending.
  • Pod Ready now waits on the sidecar's startup probe, so a slow proxy delays endpoint registration and rollouts.
  • Needs 1.29+ (beta, on by default; GA in 1.33). Check kubectl version before writing manifests that depend on it.

Your exercise

Write a Job whose main container runs sleep 5, plus a busybox sidecar running tail -f /dev/null. Apply it with the sidecar in spec.containers and watch:

kubectl get job -w

It never reaches COMPLETIONS 1/1. Now move the sidecar into initContainers with restartPolicy: Always and re-apply. Then run kubectl describe pod on each and work out the pod's effective CPU request in both cases — can you explain the difference using the two resource rules above?