Skip to content
LF Cert Trainer

Lesson 55 · Section 5: Application Lifecycle Management

Lesson 55: Init containers: work that must finish before the app starts

What init containers are, the order and rules the kubelet follows when it runs them, how they hand files to the app, what happens when one fails, and how to write and debug them fast in the exam. · 20 min read · 4 min video

1/10Init containers
0:00 / 3:54

Narrated by the local narrator voice. Keys: Space plays and pauses, J and L step, C captions, F full screen.

Why init containers exist

Many applications need something to be true before they start. The schema of the database must be migrated. A configuration file must be downloaded or rendered. A directory on a volume must belong to the right user. A Service the app depends on must already answer, or the app crashes on its first connection.

You could put all of that in the application's start script. It works, and it costs you three things:

  • A bigger, weaker image. The app image now ships git, curl, a database client or a shell, tools an attacker would be glad to find and that the app never uses after the first second.
  • Too many rights. The setup step may need a token, a password or root that the long-running application should not hold for its whole life.
  • Copied logic. Every team rewrites the same "wait until the database answers" loop inside its own image.

An init container takes that work out of the app. It is a container in the same Pod, with its own image and its own permissions, that runs before the application containers and must finish before they start.

What an init container is

Init containers run first, one at a timefirstexit 0exit 0, start the appstogetherprobesPod sandboxnetwork and volumesInit: wait-for-dbruns, then exitsInit: fetch-configruns, then exitsContainer appstarts lastContainer shipperstarts with appPod Readygets Service traffic
Init containers run first, one at a time. Each init container must exit with code 0 before the next one starts. Only after the last one do the app containers start, all together.

Parts:

  • Pod sandbox (network and volumes)
  • Init: wait-for-db (runs, then exits)
  • Init: fetch-config (runs, then exits)
  • Container app (starts last)
  • Container shipper (starts with app)
  • Pod Ready (gets Service traffic)

Connections:

  • Pod sandbox to Init: wait-for-db: first
  • Init: wait-for-db to Init: fetch-config: exit 0
  • Init: fetch-config to Container app: exit 0, start the apps
  • Container app and Container shipper: together
  • Container shipper to Pod Ready: probes

Init containers are written in spec.initContainers, a list right next to spec.containers. Each entry uses the same fields as a normal container: name, image, command, args, env, volumeMounts, resources, securityContext.

apiVersion: v1
kind: Pod
metadata:
  name: web
spec:
  initContainers:
    - name: wait-for-db
      image: busybox:1.37
      command: ["sh", "-c", "until nc -z db 5432; do echo waiting for db; sleep 2; done"]
  containers:
    - name: app
      image: nginx:1.29

What makes them different is how the kubelet treats them:

Init containerApp container
Where it is writtenspec.initContainersspec.containers
When it runsBefore every app containerAfter the last init container
How they startOne at a time, in list orderAll together
Expected toExit with code 0Keep running (in most Pods)
Probes and lifecycle hooksNot allowedAllowed
Counted in READY (1/1)NoYes
Resource requestsThe largest one countsThey are added up

Three consequences are worth knowing:

  • The command must end. An init container that runs sleep infinity, or a server that never exits, holds the Pod in Init:0/1 forever. Nothing times out for you.
  • No probes. An init container is "ready" when it has exited successfully, so livenessProbe, readinessProbe, startupProbe and lifecycle are rejected by the API server.
  • Names are shared. A name must be unique across both lists: an init container and an app container cannot both be called app.

While init containers run, the Pod's phase is Pending, its Initialized condition is False and it is not Ready. A Service therefore never sends traffic to a Pod that is still initialising.

How it works

The kubelet on the node drives the whole sequence:

  1. It creates the Pod sandbox, so the network and the volumes exist. Init containers already have the Pod's IP and can use cluster DNS, which is why "wait for a Service" works.
  2. It starts the first init container and waits. Exit code 0 marks it Completed.
  3. It starts the next one, and so on down the list.
  4. After the last one, the Initialized condition turns True and all app containers are started.
  1. Init:0/2
  2. Init:1/2
  3. PodInitializing
  4. Running
STATUS while a Pod with two init containers starts

Passing work to the app

Handing files from an init container to the appclonewrites /workreadsGit serversite contentInit: fetch-sitehas git, then exitsVolume siteemptyDirContainer nginxno git inside
Handing files from an init container to the app. The two containers have separate filesystems. A volume mounted in both is the only way the init container's work reaches the app.

Parts:

  • Git server (site content)
  • Init: fetch-site (has git, then exits)
  • Volume site (emptyDir)
  • Container nginx (no git inside)

Connections:

  • Init: fetch-site to Git server: clone
  • Init: fetch-site to Volume site: writes /work
  • Container nginx to Volume site: reads

Every container has its own root filesystem, and an init container's filesystem is discarded when it exits. Whatever it produces has to be written to a volume that the app container also mounts. An emptyDir is the usual choice: it is created empty when the Pod starts and lives as long as the Pod. The two containers may mount it at different paths; it is the same directory underneath.

When an init container fails

What happens when an init container failsAlwaysrun it againNeverInit containerrunsExit code 0CompletedNext stepnext init, or the appsRetryback-off up to 5 minExit code not 0ErrorPod FailedInit:Error, no retry
What happens when an init container fails. The Pod's restartPolicy decides. With Always or OnFailure the kubelet retries the same init container, waiting longer each time. With Never the Pod fails for good.

Parts:

  • Init container (runs)
  • Exit code 0 (Completed)
  • Next step (next init, or the apps)
  • Retry (back-off up to 5 min)
  • Exit code not 0 (Error)
  • Pod Failed (Init:Error, no retry)

Connections:

  • Init container to Exit code 0
  • Exit code 0 to Next step
  • Init container to Exit code not 0
  • Exit code not 0 to Retry: Always
  • Retry to Init container: run it again
  • Exit code not 0 to Pod Failed: Never

The Pod's restartPolicy decides what happens after a non-zero exit code:

Pod restartPolicyA failed init container isWhat you see
Always (default)restarted until it succeedsInit:Error, then Init:CrashLoopBackOff
OnFailurerestarted until it succeedsInit:Error, then Init:CrashLoopBackOff
Nevernot restarted; the Pod's phase becomes FailedInit:Error

Retries use the same back-off as any crashing container: 10 seconds, 20, 40, up to five minutes. With Always, an init container that exits with code 0 is not restarted, unlike an app container: for init containers Always behaves like OnFailure.

Under the hood · How init containers count for scheduling

App containers run at the same time, so their requests are added up. Init containers run alone, one after another, so only the largest one matters. The scheduler places the Pod using the effective request, per resource:

effective request = the higher of (largest init container request, sum of all app container requests)

A Pod whose app asks for 100m of CPU but whose init container asks for 2 CPUs needs a node with 2 free CPUs, and keeps that reservation after the init container is gone. If a small Pod stays Pending with Insufficient cpu, look at the requests of its init containers too. Limits work the same way, and the Pod's QoS class is computed from init and app containers together.

Under the hood · Init containers can run more than once

Init containers are not a "once in the life of the Pod" guarantee. They all run again when the Pod's sandbox is rebuilt, for example after the node or the container runtime restarts. And a single init container is re-run as often as it fails.

So write them to be idempotent: running twice must give the same result as running once. A script that writes into an emptyDir should cope with files that are already there (git clone into a non-empty directory fails; wget -O overwrites and is fine).

Two more rules from the same family:

  • activeDeadlineSeconds on the Pod covers the init phase as well. A slow init container can get the Pod killed.
  • On a live Pod only the image of an init container can be changed, and that change does not restart the Pod.

Init containers, app containers and sidecars

You need a container thatUseWritten in
does one job and exits before the app startsInit containerinitContainers
is the application itselfApp containercontainers
helps the app for the Pod's whole life, and must be up before itSidecar containerinitContainers, with restartPolicy: Always

A sidecar is the one exception to "must exit". It is an entry in initContainers that sets its own restartPolicy: Always. The kubelet starts it in list order like any init container, but does not wait for it to exit: once it has started, the sequence goes on, and the sidecar keeps running next to the app until the Pod stops. Sidecars may have probes. This has been a stable feature since Kubernetes 1.33, and the lessons on multi-container Pods cover it in detail.

Using it

Example · Add an init container that prepares a file for the app

Task: Pod web runs nginx:1.29. Before nginx starts, a busybox:1.37 init container named make-page must write index.html so that nginx serves it.

Generate the Pod, then add the volume, the init container and the mount:

kubectl run web --image=nginx:1.29 --dry-run=client -o yaml > web.yaml
apiVersion: v1
kind: Pod
metadata:
  name: web
spec:
  volumes:
    - name: site
      emptyDir: {}
  initContainers:
    - name: make-page
      image: busybox:1.37
      command: ["sh", "-c", "echo 'Prepared by the init container' > /work/index.html"]
      volumeMounts:
        - name: site
          mountPath: /work
  containers:
    - name: web
      image: nginx:1.29
      volumeMounts:
        - name: site
          mountPath: /usr/share/nginx/html
kubectl apply -f web.yaml
kubectl get pod web                                  # Init:0/1, then Running
kubectl exec web -- cat /usr/share/nginx/html/index.html

kubectl exec goes to the app container. It prints the line the init container wrote, which proves both the order and the shared volume.

Example · Hold the app back until a Service answers

Task: the Pod api must not start its application until the Service db accepts connections on port 5432.

spec:
  initContainers:
    - name: wait-for-db
      image: busybox:1.37
      command: ["sh", "-c", "until nc -z db 5432; do echo waiting for db; sleep 2; done"]
  containers:
    - name: api
      image: nginx:1.29
kubectl get pod api                    # Init:0/1 for as long as db does not answer
kubectl logs api -c wait-for-db        # "waiting for db", repeated
kubectl create service clusterip db --tcp=5432:5432    # plus Pods behind it, in a real case

until ...; do ...; done repeats until the test succeeds, and then the script ends with code 0. Choose the test with care: nslookup db succeeds as soon as the Service exists, even with no Pod behind it, while nc -z db 5432 needs something that really accepts the connection.

Example · Find out why a Pod is stuck in Init

A Pod orders in namespace shop shows Init:CrashLoopBackOff. Work from the outside in:

kubectl -n shop get pod orders                       # 1. which init container: Init:1/3 means the 2nd one
kubectl -n shop describe pod orders                  # 2. "Init Containers:" block: State, Reason, Exit Code; Events
kubectl -n shop logs orders -c migrate               # 3. the output of that init container
kubectl -n shop logs orders -c migrate --previous    #    and of the attempt that crashed
STATUSMeaningWhere to look
Init:N/MN of M init containers are done; number N+1 is running or waitingLogs of that container: what is it waiting for?
Init:ErrorAn init container exited with a non-zero codedescribe for the exit code, logs -c for the reason
Init:CrashLoopBackOffIt failed several times and the kubelet is backing offlogs -c <name> --previous
Init:ErrImagePull, Init:ImagePullBackOffThe init container's image cannot be pulledThe image name and tag in initContainers
PodInitializingInit is done, the app containers are startingNormal for a few seconds; longer means a slow image pull
PendingNot scheduled yet; no init container has startedFailedScheduling event, the init containers' requests

Exit code 127 means the command was not found (a typo, or a tool the image lacks) and 1 is the script's own error. The fix is usually a wrong command, a wrong image, a missing volume mount or something outside the Pod that the init container waits for.

Example · Fix an init container in a running workload

initContainers cannot be edited on a live Pod (only an image can). How you fix it depends on who owns the Pod:

# A bare Pod: export, edit, delete and recreate in one step
kubectl get pod web -o yaml > web.yaml
vi web.yaml
kubectl replace --force -f web.yaml

# A Deployment: edit the Pod template; the rollout creates new Pods that run the new init container
kubectl edit deployment api            # spec.template.spec.initContainers
kubectl rollout status deployment api

In a Deployment, a broken init container makes the rollout stall: the new Pods never become ready, the old ones keep serving, and kubectl rollout status waits. That is the safety net working.

Tricks

Common mistakes

  • A command that never ends. An init container must exit. A server, tail -f or sleep infinity blocks the Pod in Init:0/1 with no error at all.
  • Wrong indentation level. initContainers belongs under spec, at the same level as containers. Nested inside a container or placed at the top level, kubectl apply rejects the manifest with an "unknown field" error.
  • Forgetting the shared volume. Files written to the init container's own filesystem are gone when it exits. If the app "does not see" the file, check that both containers mount the same volume.
  • Reading the wrong logs. Without -c, kubectl picks the app container. The message waiting to start: PodInitializing is not the error; the init container's log is.
  • Relying on order between init containers that does not exist in the list. They run in list order, top to bottom. If one needs the output of another, it must come later in the list.
  • Adding a probe. Probes and lifecycle hooks are not allowed on init containers; the API server rejects the Pod.
  • Waiting for the wrong thing. A DNS lookup proves that a Service exists, not that the application behind it is up.

Recap

  • Init containers live in spec.initContainers and run before the app containers, one at a time, in list order.
  • Each must exit with code 0. A failure is retried with back-off (Always, OnFailure) or fails the Pod (Never); the app never starts until all have succeeded.
  • They hand files to the app through a shared volume, usually an emptyDir.
  • The scheduler uses the largest init request or the sum of the app requests, whichever is higher.
  • Debug with the status (Init:N/M, Init:Error, Init:CrashLoopBackOff), kubectl describe pod, and kubectl logs <pod> -c <init-container>.

Official docs

Quiz: check what you learned

5 questions on this lesson · about 3 min · instant feedback. Missed questions come back in your review queue.

Sign in to take the quiz and keep your score.

Practise: try it on a real cluster

A hands-on lab for this lesson. You get goals, not steps: any solution that reaches them passes.

  • Add an init container that holds an app back until its database is reachable, and repair one that waits forever.

    Build · Level 2 · standard · target 15 min

Discussion

Learners ask and answer questions here. Sign in to read and join the discussion.