https://drive.google.com/file/d/19ytBZF5JEkP5J1j1nnpysHYnfuu9UBiR/view?usp=sharing

๐Ÿ” What Is an Init Container?

โœ… Init Containers are special containers that run before the main app containers in a Pod.

๐Ÿ’ก Think of them as the "pre-flight checklist" for your app.


๐Ÿ”ง YAML Breakdown (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

๐Ÿงฉ Key Components Explained

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!


๐Ÿ“Œ Why This Pattern Matters (Real-World Use Cases)

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.


๐Ÿงช Lab: Deploy the Cow-Say Pod & See the Magic

๐Ÿ”ง Steps

# 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 |
#                 ||     ||

๐Ÿ” Observe Init Container Logs