12 Kubernetes Init Container Use Cases with YAML
12 Kubernetes init container use cases with YAML: wait-for, migrations, secrets, config, permissions, data, sysctl, plus native sidecars (1.33).
A Kubernetes init container runs to completion before the app containers in a pod start, one at a time and in order. Teams use them to wait for dependencies, run schema migrations, fetch secrets or config, fix volume permissions, pre-load data and register services. Since Kubernetes 1.33, an init container with restartPolicy: Always becomes a native sidecar that keeps running.
This guide walks through twelve use cases with working YAML, the trade-offs of each, and when another Kubernetes feature does the job better. For the wider picture of pods, the kubelet and the control plane, see our Kubernetes architecture components guide.
Key takeaways
- Init containers run sequentially; each must exit with code 0 before the next starts, and app containers start only after all of them finish.
- If an init container fails, the kubelet retries it according to the pod's
restartPolicy. WithNever, the pod is marked failed. - Regular init containers do not support liveness, readiness, startup probes or lifecycle hooks. Native sidecars do support probes.
- They can use a different image from the app, so tools such as
psql,curlor a migration binary stay out of the production image. - Init containers re-run when a pod is recreated, so every step must be idempotent.
- Not every startup task belongs in an init container. Long migrations often fit better in a Job or a Helm hook.
How init containers behave
| Property | Regular init container | Native sidecar (init container with restartPolicy: Always) | App container |
|---|---|---|---|
| When it runs | Before app containers, in order | Starts in init order, then keeps running | After all init containers complete or sidecars start |
| Must exit? | Yes, with code 0 | No | No |
| Probes | Not supported | Supported | Supported |
| Resource accounting | Highest single init request counts for scheduling | Added to app container requests | Summed |
| Typical use | Setup tasks | Proxies, log shippers | The workload |
The resource rule matters for capacity planning: the scheduler uses the larger of (the biggest init container request) or (the sum of app containers plus sidecars). A heavy init container can therefore make a pod harder to schedule even though it only runs for seconds.
1. Wait for a database or service
The classic use case: hold the app until its dependency answers. This avoids crash loops when the app container would exit on a failed connection.
initContainers:
- name: wait-for-postgres
image: postgres:16
command: ["sh", "-c"]
args:
- until pg_isready -h postgres.db.svc.cluster.local -p 5432; do
echo "waiting for postgres"; sleep 2;
done
Use this with care. Waiting at startup does not help when the database drops later, so the app still needs retry logic. Add a timeout so pods do not hang forever during an outage.
2. Run database schema migrations
Running a migration tool such as Flyway, Liquibase or Alembic in an init container keeps the schema in step with the image version.
initContainers:
- name: migrate
image: registry.example.com/api-migrations:2.3.0
command: ["flyway", "migrate"]
envFrom:
- secretRef:
name: db-credentials
The catch: a Deployment with five replicas runs five migrations at the same moment. The tools above use a lock table, but long migrations still delay every pod. For anything slow or risky, run the migration once as a Job, Helm pre-upgrade hook or Argo CD PreSync hook. Our guide to blue-green database migration covers the backward-compatible schema changes this needs.
3. Fetch secrets from an external vault
An init container can authenticate to HashiCorp Vault or a cloud secrets manager, write the secret to an in-memory volume, and exit. The app reads the file and never needs vault credentials or tools.
volumes:
- name: secrets
emptyDir:
medium: Memory
initContainers:
- name: fetch-secrets
image: hashicorp/vault:1.17
command: ["sh", "-c", "vault kv get -field=password secret/api > /secrets/db-password"]
volumeMounts:
- name: secrets
mountPath: /secrets
This pattern fetches once. If secrets rotate while the pod runs, use the Vault Agent sidecar injector or the Secrets Store CSI Driver instead. medium: Memory keeps the secret off the node disk.
4. Render configuration templates
Some apps need a config file built from environment values, the pod IP or the pod name. An init container can render a template from a ConfigMap into a shared emptyDir.
initContainers:
- name: render-config
image: alpine:3.20
command: ["sh", "-c", "sed \"s/__POD_NAME__/$POD_NAME/\" /templates/app.conf > /config/app.conf"]
env:
- name: POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
volumeMounts:
- { name: templates, mountPath: /templates }
- { name: config, mountPath: /config }
StatefulSets use this a lot: each replica reads its ordinal from the hostname and writes a different config, for example to pick a primary or replica role.
5. Fix volume ownership and permissions
When a non-root app mounts a volume that a storage driver created as root, writes fail. Try securityContext.fsGroup first. If the volume type ignores fsGroup, or you need a specific owner, a short init container can fix it.
initContainers:
- name: fix-perms
image: busybox:1.36
command: ["sh", "-c", "chown -R 10001:10001 /data"]
securityContext:
runAsUser: 0
volumeMounts:
- { name: data, mountPath: /data }
This init container runs as root, which the Pod Security "restricted" profile rejects. Prefer fsGroup with fsGroupChangePolicy: OnRootMismatch where the volume supports it. File permission details for containers are in our Linux permissions for DevOps guide.
6. Download or pre-load data
Machine learning models, GeoIP databases or static assets can be pulled from object storage before the app starts, keeping the image small.
initContainers:
- name: fetch-model
image: amazon/aws-cli:2.17.0
command: ["aws", "s3", "cp", "s3://models-bucket/v4/model.bin", "/models/model.bin"]
volumeMounts:
- { name: models, mountPath: /models }
Large downloads slow every pod start and every scale-up. If startup speed matters, consider baking data into the image or using a node-level cache. Kubernetes also has image volumes (an OCI image mounted as a read-only volume), which reached beta in recent releases; check the docs for your cluster version before relying on it.
7. Clone a Git repository
Static sites, documentation servers and some config-driven tools pull content from Git at startup.
initContainers:
- name: git-clone
image: alpine/git:2.45.2
args: ["clone", "--depth", "1", "--branch", "main", "https://github.com/example/site.git", "/content"]
volumeMounts:
- { name: content, mountPath: /content }
The old gitRepo volume type is deprecated in Kubernetes, so the init container approach (or a git-sync sidecar for continuous updates) is the replacement. Shallow clones keep startup fast.
8. Set kernel parameters for a single pod
Search engines such as Elasticsearch and OpenSearch need vm.max_map_count raised on the node. Helm charts for these tools have used a privileged init container for this.
initContainers:
- name: sysctl
image: busybox:1.36
command: ["sysctl", "-w", "vm.max_map_count=262144"]
securityContext:
privileged: true
A privileged container changes the whole node, not just the pod. Where you can, set the value at node level (node image, DaemonSet run by the platform team, or a machine config) and use the pod securityContext.sysctls field only for namespaced "safe" sysctls.
9. Register with a service registry or cluster
Clustered software such as some databases and message brokers needs each member to announce itself or find peers before it starts. An init container can query DNS for the headless service and write the peer list.
initContainers:
- name: discover-peers
image: busybox:1.36
command: ["sh", "-c", "nslookup my-db-headless.db.svc.cluster.local | grep Address | tail -n +2 > /config/peers"]
volumeMounts:
- { name: config, mountPath: /config }
Many mature databases now ship an Operator that handles membership, which is safer than hand-written scripts. Read more in Kubernetes Operators for stateful apps.
10. Verify an image or artifact before start
Some teams check a checksum or signature of a downloaded artifact before the app uses it. An init container that exits non-zero on mismatch keeps a tampered file from ever loading.
initContainers:
- name: verify
image: alpine:3.20
command: ["sh", "-c", "cd /models && sha256sum -c model.sha256"]
volumeMounts:
- { name: models, mountPath: /models }
For container images themselves, admission-time verification (Sigstore policy-controller, Kyverno image verification) is the better place, because it stops the pod before any container runs.
11. Network setup for the pod
Service meshes historically used an init container with NET_ADMIN to write iptables rules that redirect traffic to the sidecar proxy. Istio's istio-init is the best-known example. Istio also offers a CNI plugin that removes the need for this privileged init container, and its ambient mode avoids per-pod sidecars entirely.
The lesson for your own workloads: any init container that needs NET_ADMIN or privileged mode is a security exception. Document it and check whether a CNI plugin or node-level setup can replace it. See sidecar proxies in service meshes for the traffic side.
12. Native sidecars: start helpers before the app
The newest use case. Setting restartPolicy: Always on an init container makes it a sidecar: Kubernetes starts it in init order, does not wait for it to exit, keeps it running alongside the app, and stops it after the app containers on shutdown. The feature was enabled by default from 1.29 and is stable in 1.33.
initContainers:
- name: log-shipper
image: fluent/fluent-bit:3.1
restartPolicy: Always
startupProbe:
httpGet: { path: /api/v1/health, port: 2020 }
volumeMounts:
- { name: logs, mountPath: /var/log/app }
containers:
- name: app
image: registry.example.com/app:5.0.1
volumeMounts:
- { name: logs, mountPath: /var/log/app }
This solves two old problems: the proxy or log shipper is ready before the app sends its first request, and in Jobs the sidecar no longer keeps the pod running after the main container exits.
When not to use an init container
| Task | Better option | Why |
|---|---|---|
| Long or risky schema migration | Job, Helm hook, Argo CD sync hook | Runs once per release, not once per pod |
| Secrets that rotate | CSI Secrets Store driver or vault agent sidecar | Updates while the pod runs |
| Waiting for slow app warm-up | startupProbe on the app | Probe handles it without extra containers |
| Node kernel tuning | Node image or platform DaemonSet | Avoids privileged workload pods |
| Image signature checks | Admission policy | Blocks before anything runs |
Debugging init containers
kubectl get pod api-7c9f -o wide # STATUS shows Init:0/2, Init:Error, Init:CrashLoopBackOff
kubectl describe pod api-7c9f # events and per-init-container state
kubectl logs api-7c9f -c migrate # logs from a specific init container
kubectl logs api-7c9f -c migrate --previous
Init:1/3 means one of three init containers has finished. A pod stuck in Init:0/1 is usually waiting on a dependency loop with no timeout. If the pod spec changes the init container image, the pod is recreated and init containers run again.
Best practices
- Make every init step idempotent; it will re-run on rescheduling and restarts.
- Set resource requests and limits on init containers; they count toward scheduling.
- Pin image tags or digests, just as for app containers.
- Add timeouts to wait loops and fail clearly with a log message.
- Avoid privileged init containers; when unavoidable, record the exception in your policy tool.
- Keep init images small so pod start time stays low during scale-out.
To practise these patterns on a real cluster, the CKAD course covers multi-container pods, init containers and probes, in our Kharadi, Pune classroom or live online. Related reading: liveness and readiness probes and Helm for deployment management.
Frequently asked questions
What is an init container in Kubernetes?
A container in the pod spec under initContainers that runs to completion before the app containers start. Multiple init containers run one after another in the listed order.
What happens if an init container fails?
The kubelet restarts it according to the pod restartPolicy, with back-off. App containers do not start until it succeeds. With restartPolicy Never, the pod fails.
Can init containers have readiness probes?
Regular init containers cannot use liveness, readiness or startup probes. Native sidecars, defined with restartPolicy Always, can.
What is a native sidecar container?
An init container with restartPolicy Always. It starts before app containers, keeps running beside them, and stops after them. It is stable in Kubernetes 1.33.
Should database migrations run in an init container?
Short, lock-protected migrations can. Long or risky ones are safer as a Job or a Helm or Argo CD hook that runs once per release instead of once per replica.
Do init containers share volumes with app containers?
Yes. They can mount the same pod volumes, which is how they pass rendered config, secrets or downloaded data to the app.
How do init container resources affect scheduling?
The scheduler uses the higher of the largest single init container request or the total of app containers and sidecars.
How do I see logs from an init container?
Run kubectl logs POD -c INIT_CONTAINER_NAME. Add --previous to read the log of the last failed attempt.
References
What's Your Reaction?
Like
0
Dislike
0
Love
0
Funny
0
Angry
0
Sad
0
Wow
0