https://drive.google.com/file/d/19ytBZF5JEkP5J1j1nnpysHYnfuu9UBiR/view?usp=sharing
โ Init Containers are special containers that run before the main app containers in a Pod.
- They must complete successfully before the main app starts.
- Used for setup tasks: download config, wait for DB, generate certs, run migrations, etc.
- They do not run concurrently with app containers.
๐ก Think of them as the "pre-flight checklist" for your app.
cow-say-with-init.yml)apiVersion: v1
kind: Pod
metadata:
name: nginx
spec:
restartPolicy: Always
volumes:
- name: data
emptyDir: {}
initContainers:
- name: nginx-init
image: busybox
command: ["/bin/sh", "-c"]
args:
- echo "<pre>Hello Kubernetes</pre>" > /data/index.html
volumeMounts:
- name: data
mountPath: /data
containers:
- name: nginx
image: nginx:1.11
volumeMounts:
- name: data
mountPath: /usr/share/nginx/html
| Section | Purpose |
|---|---|
volumes: - name: data |
Creates an emptyDir volume (temporary storage on the node). Lives as long as the Pod. |
initContainers |
Runs first. Uses docker/whalesay (a fun image with cowsay). |
command + args |
Runs shell command: generates a cow saying "Hello Kubernetes" โ saves as index.html. |
volumeMounts (init) |
Mounts data volume at /data โ writes index.html there. |
containers (main app) |
Runs nginx, which serves static files from /usr/share/nginx/html. |
volumeMounts (nginx) |
Mounts the same data volume โ so it serves the index.html created by init! |
๐ฏ Result: When you visit the nginx Pod, you see a cow saying "Hello Kubernetes" โ generated at startup by the init container!
| Scenario | How Init Containers Help |
|---|---|
| Wait for DB | Run a script that pings DB until ready โ then start app. |
| Fetch config | Download secrets/config from Vault or Git before app starts. |
| Migrate DB | Run rails db:migrate before launching Rails app. |
| Generate certs | Create TLS certs for the main app to use. |
โ Advantage over sidecar: Init containers run once and exit โ no resource waste.
# 1. Apply the Pod
kubectl apply -f cow-say-with-init.yml
# 2. Watch the Pod phases
kubectl get pods -w
# You'll see:
# nginx 0/1 Init:0/1 โ then โ nginx 1/1 Running
# 3. Once running, port-forward to access nginx
kubectl port-forward pod/nginx 8080:80
# 4. Open browser or run:
curl <http://localhost:8080>
# ๐ฎ You should see:
# _______________________
# < Hello Kubernetes! >
# -----------------------
# \\\\ ^__^
# \\\\ (oo)\\\\_______
# (__)\\\\ )\\\\/\\\\
# ||----w |
# || ||