What is Init Container in Kubernetes?
An Init Container is a special container that runs before your main application container starts.
👉 Think of it like setup/initialization step
Before your app starts, something must be ready → init container handles that.
Key Points (Very Important)
- Runs before main container
- Runs only once and completes
- Runs in sequence (if multiple init containers)
- If it fails → main container will NOT start
Why we use Init Containers (Real Use Cases)
Real-world use cases (very useful in your EKS/Kubernetes work):
1. Wait for dependency (most common)
Example:
- Wait until DB is up before app starts
2. Create config files
- Download config from Git / S3
3. Prepare volume/data
- Create directories
- Copy files
4. Security / permissions setup
- Set file permissions before app runs
👉 Basically:
👉 “Do setup → THEN start app”
YAML Example
apiVersion: v1kind: Podmetadata: name: init-demospec: initContainers: - name: init-myservice image: alpine command: ['sh', '-c', 'echo "Preparing data..."; sleep 5; mkdir -p /data/logs'] volumeMounts: - name: shared-data mountPath: /data containers: - name: main-app image: nginx ports: - containerPort: 80 volumeMounts: - name: shared-data mountPath: /data volumes: - name: shared-data emptyDir: {}
What happens here?
Step-by-step:
- Init container runs first
→ prints message
→ waits 5 sec
→ creates/data/logs - After success ✅
→ main container (nginx) starts - Both share same volume (
emptyDir)
→ data created is available to app
Commands to Run & Verify
1. Apply YAML
kubectl apply -f init-demo.yaml
2. Check Pod Status
kubectl get pods
3. Describe Pod (Detailed)
kubectl describe pod init-demo
4. Check Init Container Logs
kubectl logs init-demo -c init-myservice
5. After success
kubectl get pods
Another Real Example
initContainers:- name: wait-for-db image: busybox command: - sh - -c - | until nc -z mydb 5432; do echo "Waiting for DB..."; sleep 2; done
Important Difference (Init vs Normal Container)
| Feature | Init Container | Normal Container |
|---|---|---|
| Start time | Before app | With pod |
| Runs | One time | Continuous |
| Purpose | Setup | Application |
| Failure | Blocks app | Can restart |