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
containersentry exits. Your Envoy or Fluent Bit sidecar never exits, so the Job sits inRunningforever and the CronJob piles up unfinished runs. - Startup race. Entries in
containersstart in parallel. The app's first outbound call fires before the proxy is listening —connection refusedfor 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
containersand 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
appexits - Terminates after the main containers, in reverse order, so you get a clean drain
The gotchas
restartPolicy: Alwaysis legal only on aninitContainersentry, andAlwaysis the only value allowed there. Inspec.containersit 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 a500m/512Miproxy intoinitContainersand the scheduler suddenly needs 500m more per pod — pods that used to fit goPending. - Pod
Readynow 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 versionbefore 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?