An init container runs to completion before the app containers start, in order, and can share volumes with them. It is the place for setup and preconditions: preparing a directory, running a migration or waiting for a dependency, so the app starts only when its environment is ready.
Before you start
You should be comfortable with pods and volumes. This article covers init containers and their ordering.
Step-by-step walkthrough
Step 1: Order the sequence
Init containers run one at a time in the declared order, and each must exit successfully before the next begins. If any fails, the pod is restarted according to its policy, so a failing precondition holds the app back instead of letting it start broken.
Step 2: Gate on dependencies
An init container can poll a database or a service until it is reachable, so the app does not crash-loop waiting for a dependency. Once the init exits, the app starts knowing the dependency is up, which simplifies the app’s own startup.
Step 3: Share data through volumes
An init container writes to a volume that the app container mounts read-write, so setup artifacts are available without baking them into the image. Use this for generated config or a populated cache directory.
Worked scenario
An init container waits for a database before the app starts.
spec:
initContainers:
- name: wait-for-db
image: postgres:16
command: ["sh", "-c", "until pg_isready -h db; do sleep 2; done"]
containers:
- name: api
image: api:1.2.3Walk through the example
The init container polls db until it accepts connections, then exits, and only then does api start. The app no longer needs retry logic for a missing database at startup, and the pod does not sit in a crash loop. Ordering guarantees the app sees a reachable dependency.
Common mistake
Putting long waits in the main app instead of an init container, so the app is in a running-but-not-ready state and generates noise. Another is confusing init containers with sidecars: init runs to completion before start, sidecars run alongside the app.
Verify the behavior
Start the pod without the dependency and confirm it stays in Init until the dependency is up. Break the dependency and confirm the pod does not start. Check that the app binds only after the init container exits successfully.
Interview exercise
What is the difference between an init container and a sidecar?
Answer and reasoning
An init container runs to completion before the app containers start and then exits, which suits one-time setup and preconditions. A sidecar runs alongside the app for the pod’s lifetime, providing an ongoing service such as a proxy or a log shipper. The lifecycle, not the image, is what distinguishes them.
Continue learning
Compare startup gating in Pod lifecycle and probes in Probe separation. Read the Kubernetes init containers documentation and try the Kubernetes interview questions.