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
This entry was posted in DevOps on by .
Unknown's avatar

About SandeepSingh

Hi, I am working in IT industry with having more than 15 year of experience, worked as an Oracle DBA with a Company and handling different databases like Oracle, SQL Server , DB2 etc Worked as a Development and Database Administrator.

Leave a Reply