What are init containers in Kubernetes and when would you use them?
Init containers run one after another, to completion, before the app containers start. Use them for setup such as waiting for a database, running migrations or fetching config. If one fails, the Pod restarts it.
Explain it simply
Before a cricket match, the groundsman rolls the pitch and marks the crease. Only after that do the players walk in. Init containers are the groundsman.
Each init container must exit successfully, in the order listed, before the next one begins, and all must finish before the main containers start. They can use different images with tools the app image lacks, such as git, curl or a database client, and they can write results to a shared volume. Examples: wait until db:5432 is reachable, run a schema migration, download a model file, set file permissions.
While init containers run, kubectl get pods shows Init:0/1. If an init container keeps failing, the Pod stays stuck and the app never starts, so check kubectl logs pod -c init-name.
Example
spec:
initContainers:
- name: wait-for-db
image: busybox:1.36
command: ['sh','-c','until nc -z db 5432; do sleep 2; done']
containers:
- name: app
image: myapp:1.0What to say in the interview
"Init containers run sequentially to completion before the app containers start. I use them for waiting on dependencies, migrations or fetching files, and I debug a stuck Pod with kubectl logs -c on the init container."
Common mistakes
- Forgetting that a failing init container blocks the entire Pod.