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
Official competency this lesson covers
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
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 container | App container | |
|---|---|---|
| Where it is written | spec.initContainers | spec.containers |
| When it runs | Before every app container | After the last init container |
| How they start | One at a time, in list order | All together |
| Expected to | Exit with code 0 | Keep running (in most Pods) |
Probes and lifecycle hooks | Not allowed | Allowed |
Counted in READY (1/1) | No | Yes |
| Resource requests | The largest one counts | They 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 inInit:0/1forever. Nothing times out for you. - No probes. An init container is "ready" when it has exited successfully, so
livenessProbe,readinessProbe,startupProbeandlifecycleare 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:
- 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.
- It starts the first init container and waits. Exit code 0 marks it
Completed. - It starts the next one, and so on down the list.
- After the last one, the
Initializedcondition turnsTrueand all app containers are started.
- Init:0/2
- Init:1/2
- PodInitializing
- Running
Passing work to 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
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 restartPolicy | A failed init container is | What you see |
|---|---|---|
Always (default) | restarted until it succeeds | Init:Error, then Init:CrashLoopBackOff |
OnFailure | restarted until it succeeds | Init:Error, then Init:CrashLoopBackOff |
Never | not restarted; the Pod's phase becomes Failed | Init: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:
activeDeadlineSecondson the Pod covers the init phase as well. A slow init container can get the Pod killed.- On a live Pod only the
imageof an init container can be changed, and that change does not restart the Pod.
Init containers, app containers and sidecars
| You need a container that | Use | Written in |
|---|---|---|
| does one job and exits before the app starts | Init container | initContainers |
| is the application itself | App container | containers |
| helps the app for the Pod's whole life, and must be up before it | Sidecar container | initContainers, 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
| STATUS | Meaning | Where to look |
|---|---|---|
Init:N/M | N of M init containers are done; number N+1 is running or waiting | Logs of that container: what is it waiting for? |
Init:Error | An init container exited with a non-zero code | describe for the exit code, logs -c for the reason |
Init:CrashLoopBackOff | It failed several times and the kubelet is backing off | logs -c <name> --previous |
Init:ErrImagePull, Init:ImagePullBackOff | The init container's image cannot be pulled | The image name and tag in initContainers |
PodInitializing | Init is done, the app containers are starting | Normal for a few seconds; longer means a slow image pull |
Pending | Not scheduled yet; no init container has started | FailedScheduling 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 -forsleep infinityblocks the Pod inInit:0/1with no error at all. - Wrong indentation level.
initContainersbelongs underspec, at the same level ascontainers. Nested inside a container or placed at the top level,kubectl applyrejects 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 messagewaiting to start: PodInitializingis 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
lifecyclehooks 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.initContainersand 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, andkubectl 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.