How Init Containers Enhance Kubernetes Deployments

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: v1
kind: Pod
metadata:
name: init-demo
spec:
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:

  1. Init container runs first
    β†’ prints message
    β†’ waits 5 sec
    β†’ creates /data/logs
  2. After success βœ…
    β†’ main container (nginx) starts
  3. 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)

FeatureInit ContainerNormal Container
Start timeBefore appWith pod
RunsOne timeContinuous
PurposeSetupApplication
FailureBlocks appCan restart