An init container is an ordinary container that Kubernetes runs to completion, one at a time, before any application container in the pod starts. Each one must exit 0 before the next begins; if one fails, the kubelet retries it according to the pod’s restartPolicy and the pod never progresses past Init:. That single guarantee is what makes init containers useful for setup work — fetching config into a shared volume, fixing file ownership, running a migration — and useless for anything that needs to keep running. For long-lived helpers, Kubernetes now has a separate answer: a native sidecar, which is an init container with restartPolicy: Always. This guide covers the ordering rules, the surprising resource-request arithmetic, the real patterns worth using, and how to read a failing init container.
What you’ll accomplish
- Write init containers that run in a known order and block the app until their work is done.
- Compute a pod’s effective resource request correctly, including the sidecar interaction that trips up capacity planning.
- Recognize
Init:0/2,Init:ErrorandInit:CrashLoopBackOffon sight and pull the right logs. - Convert a long-running helper from a regular container into a native sidecar.
- Know which of the four classic init-container patterns are worth keeping and which are a smell.
Prerequisites
- A Kubernetes cluster and a namespace you can deploy into, with
kubectlpermission toapply,get,describe, andlogs. - Kubernetes 1.29 or newer for native sidecars. Being precise about the boundary: the
SidecarContainersfeature gate was alpha in 1.28, went beta and on by default in 1.29, and graduated to stable in 1.33. On 1.28 you must enable the gate yourself; below 1.28 therestartPolicyfield on an init container is rejected by the API server. Plain init containers have worked since 1.6 and need nothing special. - A workload to attach them to. The examples use a Deployment named
apiin namespacedemo.
How it works
The kubelet processes the initContainers list in the order you wrote it. It starts the first one, waits for it to terminate, checks the exit code, and only then starts the second. App containers in containers do not exist yet — no image is even pulled for them until the init phase is done. Once every init container has exited 0, all app containers start in parallel, and only then do their liveness, readiness, and startup probes come into play.
Three consequences follow from that model:
- Init containers cannot have liveness, readiness, or startup probes. The API server rejects them. A container that is expected to exit has nothing to be “ready” for. The exception is a native sidecar, which is expected to keep running and therefore does accept probes and lifecycle hooks.
- A failure restarts the sequence, not just the container. If
restartPolicyisAlwaysorOnFailure, the kubelet restarts the failed init container with exponential backoff. If it isNever, the whole pod is markedFailedimmediately and nothing retries. Deployments and StatefulSets only permitAlwaysin the pod template, so retry-with-backoff is what you will normally get. - Resource requests are computed differently. Init containers never run at the same time as app containers, so the scheduler does not add them together. The pod’s effective request for each resource is the higher of: the largest single init container’s request, or the sum of all app container requests. A 2 GiB init container in a pod whose app containers request 512 MiB makes the pod need 2 GiB of schedulable memory — permanently, for the entire life of the pod, even though nothing uses it after the first thirty seconds.
Native sidecars change that arithmetic. Because a sidecar keeps running alongside the app containers, its request is counted in the sum side of that comparison, not the max side. And because a sidecar is already running while any init container declared after it runs, the kubelet adds the sidecar’s request on top when evaluating those later init containers. In practice: sum your app containers and your sidecars, compare that total against your largest plain init container plus any sidecars ahead of it, and take the larger. Get this wrong and pods sit Pending with Insufficient memory for reasons that are not visible anywhere in the app spec.
Step-by-step
1. Start with the shared-volume pattern. This is the pattern that justifies init containers most clearly: the init container writes files into an emptyDir, exits, and the app container reads them. The volume exists before any container runs, so the handoff is enforced by the pod lifecycle rather than by timing.
apiVersion: apps/v1
kind: Deployment
metadata:
name: api
namespace: demo
spec:
replicas: 2
selector:
matchLabels:
app: api
template:
metadata:
labels:
app: api
spec:
initContainers:
- name: init-fetch-config
image: busybox:1.36
command: ["sh", "-c", "wget -qO /shared/app.conf http://config-svc/app.conf"]
volumeMounts:
- name: shared-config
mountPath: /shared
resources:
requests:
cpu: 50m
memory: 64Mi
containers:
- name: api
image: ghcr.io/example/api:1.4.0
volumeMounts:
- name: shared-config
mountPath: /shared
readOnly: true
resources:
requests:
cpu: 500m
memory: 512Mi
volumes:
- name: shared-config
emptyDir: {}
kubectl apply -f deployment.yaml
deployment.apps/api created
2. Watch the init phase in the status column. The STATUS field reports progress as Init:<completed>/<total>, which is the fastest way to see where a pod is stuck.
kubectl get pod -n demo -l app=api -w
NAME READY STATUS RESTARTS AGE
api-7d4f9c6b58-2xqkp 0/1 Init:0/1 0 3s
api-7d4f9c6b58-2xqkp 0/1 PodInitializing 0 9s
api-7d4f9c6b58-2xqkp 1/1 Running 0 12s
PodInitializing means every init container finished and the kubelet is now starting app containers.
3. Add a second init container for ordered setup. Order is positional. This one fixes ownership on a mounted volume before the app — which runs as a non-root user — tries to write to it.
- name: init-fix-perms
image: busybox:1.36
command: ["sh", "-c", "chown -R 1000:1000 /data"]
securityContext:
runAsUser: 0
volumeMounts:
- name: data
mountPath: /data
With two init containers, the status column now counts to two:
NAME READY STATUS RESTARTS AGE
api-7d4f9c6b58-2xqkp 0/1 Init:0/2 0 4s
api-7d4f9c6b58-2xqkp 0/1 Init:1/2 0 11s
4. Convert long-running helpers into native sidecars. A log shipper, a proxy, or a credential refresher does not belong in containers if the app depends on it being up first. Declared as an init container with restartPolicy: Always, it starts in init order, the kubelet moves on to the next init container as soon as it has started (not exited), and it keeps running for the life of the pod.
- name: log-shipper
image: fluent/fluent-bit:3.0
restartPolicy: Always
startupProbe:
httpGet:
path: /api/v1/health
port: 2020
failureThreshold: 20
periodSeconds: 3
resources:
requests:
cpu: 100m
memory: 128Mi
restartPolicy: Always is the only value the API accepts on an init container. On an older cluster the request is rejected outright:
error validating data: ValidationError(Deployment.spec.template.spec.initContainers[1]):
unknown field "restartPolicy" in io.k8s.api.core.v1.Container
Sidecars count in the READY column, so a pod with one app container and one sidecar reports 2/2 rather than 1/1, and they are terminated in reverse order after the app containers stop — which is what keeps the log shipper alive long enough to flush the app’s final lines.
5. Check the resource arithmetic before you ship it. With the spec above — app api at 512Mi, sidecar log-shipper at 128Mi, plain init containers at 64Mi — the effective pod memory request is max(512Mi + 128Mi, 64Mi + 128Mi) = 640Mi. Confirm what the scheduler actually charged:
kubectl describe node <node-name> | grep -A5 "Allocated resources"
Allocated resources:
Resource Requests Limits
cpu 650m (16%) 0 (0%)
memory 640Mi (8%) 0 (0%)
Validate it works
Confirm the ordering held. kubectl describe reports each init container’s terminal state, and the exit code is the part that matters:
kubectl describe pod -n demo -l app=api
Init Containers:
init-fetch-config:
State: Terminated
Reason: Completed
Exit Code: 0
Ready: True
init-fix-perms:
State: Terminated
Reason: Completed
Exit Code: 0
Ready: True
Read an init container’s logs by name. kubectl logs defaults to the app container and will tell you it cannot find the init container’s output unless you name it with -c:
kubectl logs api-7d4f9c6b58-2xqkp -n demo -c init-fetch-config
Connecting to config-svc (10.96.41.7:80)
saving to '/shared/app.conf'
'/shared/app.conf' saved
After a retry, the interesting output is in the previous attempt, not the current one:
kubectl logs api-7d4f9c6b58-2xqkp -n demo -c init-fix-perms --previous
Confirm the app actually received the files.
kubectl exec -n demo api-7d4f9c6b58-2xqkp -c api -- ls -l /shared
-rw-r--r-- 1 root root 1842 Jul 29 14:02 app.conf
Troubleshooting
Init:Errorwith a non-zero exit code. The init container ran and failed. Get the exit code fromkubectl describe pod, then the reason fromkubectl logs pod -c <init-name> --previous. Exit code 1 is usually the command itself failing; 126 and 127 mean the binary is not executable or not present in that image — a common result of copying acommandfrom one image to another. The same exit-code reasoning applies to app containers; see diagnosing CrashLoopBackOff in Kubernetes.Init:CrashLoopBackOffthat never clears. The kubelet is retrying with backoff up to five minutes between attempts, so a pod can sit here for a long time looking idle. If the init container is waiting on a dependency that will not come back, the pod will wait forever. Check the Events block forBack-off restarting failed container <init-name>and fix the dependency rather than the pod.- Stuck at
Init:0/1with no logs at all. The container never started. Almost always an image problem:ImagePullBackOffon the init container shows indescribeunder the init container’s state, not in the top-level status string. Check the image tag and the pull secret. - Pods
PendingwithInsufficient memoryafter adding an init container. You hit the max-versus-sum rule. A large one-shot init container raises the pod’s request for its whole lifetime. Give the init container a request sized to what it actually needs instead of copying the app container’s block, and re-check withkubectl describe podunderEventsfor the scheduler’s message. - The sidecar starves the app on a tight node. Sidecar requests add to the app’s, so a mesh proxy plus a log shipper can quietly double a small pod’s footprint across hundreds of replicas. Size sidecars deliberately and confirm the totals on the node before rolling out fleet-wide.
When this is the wrong approach
A wait-for-dependency init container is usually worse than an app that retries. The classic until nc -z db 5432; do sleep 2; done loop feels tidy, but it moves the retry logic outside the app, where it only covers startup. Your app still has to survive the database restarting an hour later — so you need connection retry in the app regardless, and once you have it, the init container is redundant. Worse, it converts a recoverable condition into Init:CrashLoopBackOff, hides the real error behind a generic timeout, and delays the pod becoming schedulable during an incident when you want capacity back fast. Make the app retry its own connections with backoff, expose that state through a readiness probe, and let the pod come up. See liveness, readiness, and startup probes for the probe that actually belongs here.
Init containers do not give you run-exactly-once. Every replica runs its own init containers, so a schema migration in an init container with replicas: 3 runs three times concurrently, and a rollout runs it again on every new pod. If your migration tool takes a database advisory lock and is genuinely idempotent, this is survivable. If it does not, use a Kubernetes Job or a Helm pre-upgrade hook that runs once per release, and keep the init container for the far cheaper check of whether the schema version is high enough to serve.
Fixing volume permissions is often better handled by the platform. securityContext.fsGroup on the pod makes the kubelet set group ownership on the volume for you, without a privileged root init container in your spec. Reach for a chown init container only when the CSI driver in play does not honour fsGroup.
Setup that belongs in the image belongs in the image. If the init container is unpacking assets or generating a file that never changes between deployments, it is build-time work running at every pod start, on every node, forever. Bake it into the image instead.
The authoritative references are the Kubernetes documentation on init containers and on sidecar containers, which specify the ordering and resource rules exactly.
If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.