What is an Init Container in Kubernetes?

What is an Init Container in Kubernetes?

In Kubernetes, an Init Container is a specialized container that runs before the main application container starts in a Pod.

It is used to perform setup tasks such as:
✅ Waiting for a service or dependency to become available
✅ Initializing databases or configurations
✅ Downloading necessary files before the main container starts

Key Features of Init Containers:
1. Runs Before Main Containers: The Pod’s main containers do not start until all Init Containers complete successfully.
2. Runs Sequentially: If multiple Init Containers are defined, they run one after another in the specified order.
3. Different from Main Containers: They can have separate images, configurations, and permissions from the main container.
4. Restart on Failure: If an Init Container fails, Kubernetes restarts it until it succeeds, or the Pod fails.

Use Cases:
✅ Ensuring database migrations complete before app startup
✅ Checking dependencies like APIs or services before launching
✅ Setting up environment configurations before execution

Scenario:
Ensuring a Database is Ready Before the App Starts

Let’s say you have a Node.js application running in a container, but it depends on a PostgreSQL database. You want to make sure the database is ready before starting the application.

Kubernetes Pod with Init Container:

apiVersion: v1
kind: Pod
metadata:
name: web-app
spec:
initContainers:
- name: init-db
image: busybox
command: ['sh', '-c', 'until telnet db-service 5432; do echo "Waiting for DB..."; sleep 2; done']

containers:
- name: nodejs-app
image: my-nodejs-app
env:
- name: DATABASE_URL
value: "postgres://user:password@db-service:5432/mydb"
ports:
- containerPort: 3000

How It Works:

1. The Init Container (init-db) runs first and waits until the PostgreSQL service (db-service) is available on port 5432.
2. It uses telnet db-service 5432 to check if the database is reachable.
3. Once the database is up, the Node.js application (nodejs-app) starts with the DATABASE_URL environment variable pointing to the database.

Why Use an Init Container Here?

✅Prevents the app from crashing due to a missing database.
✅ Ensures a smooth startup process.
✅ Avoids unnecessary retry logic in the app’s code.

Troubleshooting:

90% statup issues come with init, you can inspect logs using:
kubectl logs <pod-name> -c <init-container-name> --previous