Init Containers

Initialization workflows in Kubernetes: how init containers run, why they matter, and how to debug them when things go wrong. Synthesized from CKA Day 11 — Multi Container Pod Kubernetes: Sidecar vs Init Container.

What Is an Init Container?

An init container is a special container that runs before the main application containers in a Pod. Init containers are defined in spec.initContainers and are designed to perform setup tasks that must complete successfully before the application starts.

Key properties:

  • Run sequentially in the order they appear in the YAML
  • Each init container must exit with code 0 before the next one starts
  • If any init container fails, Kubernetes restarts the Pod according to restartPolicy
  • Main containers do not start until all init containers succeed

Exam Trap: Init containers do not support livenessProbe, readinessProbe, or startupProbe. If you see these fields in an init container spec, the Pod will fail validation. Source: CKA Day 11

Common Use Cases

Use CaseExample
Dependency waitingPoll a database or API until it is reachable
Configuration generationRender templates from ConfigMaps/Secrets into files
Permission fixeschmod or chown on shared volumes before the main app starts
Schema migrationsRun database migrations before application startup
Secrets decryptionDecrypt secrets from a KMS into a shared volume
Network setupConfigure iptables rules or service mesh sidecar injection

Init Container YAML

apiVersion: v1
kind: Pod
metadata:
  name: init-demo
spec:
  initContainers:
  - name: wait-for-db
    image: busybox:1.36
    command: ['sh', '-c']
    args:
    - |
      until nc -z db 5432; do
        echo "Waiting for database..."
        sleep 2
      done
  - name: run-migrations
    image: migrate/migrate
    command: ["migrate", "-path", "/migrations", "-database", "postgres://db:5432/app", "up"]
    volumeMounts:
    - name: migrations
      mountPath: /migrations
  containers:
  - name: app
    image: my-app:1.0
    ports:
    - containerPort: 8080
    volumeMounts:
    - name: migrations
      mountPath: /migrations
  volumes:
  - name: migrations
    emptyDir: {}

In this example:

  1. wait-for-db polls the database port until it is open
  2. run-migrations applies database schema changes
  3. Only then does the app container start

Resource Considerations

Init containers affect Pod scheduling because Kubernetes uses the highest resource request/limit across all init and regular containers to determine the Pod’s total resource requirement.

Container TypeResource Impact
Init containersHighest init container request + highest regular container request = scheduling requirement
Regular containersSum of all regular container requests = runtime requirement

Best practice: Keep init containers lightweight. A heavy init container can cause unnecessary scheduling pressure (large node requirements) even though it only runs briefly. Source: CKA Day 11

Troubleshooting Init Containers

Check Pod Status

kubectl get pod init-demo
# STATUS: Init:0/2  → 0 of 2 init containers have completed
# STATUS: Init:1/2  → 1 of 2 completed, waiting on the second
# STATUS: Init:Error → The current init container failed

Read Init Container Logs

# Get logs from a specific init container
kubectl logs init-demo -c wait-for-db
 
# If the pod has restarted, get logs from the previous instance
kubectl logs init-demo -c wait-for-db --previous

Describe for Events

kubectl describe pod init-demo

Look for:

  • Init Containers section showing each init container’s state
  • Events showing Created container, Started container, or Back-off restarting failed container

Common Failure Modes

FailureCauseFix
Init:CrashLoopBackOffInit container exits non-zeroFix the script/command; add retries or timeouts
Init:0/1 foreverWaiting condition never satisfiedVerify dependencies are running and reachable
ImagePullBackOff on initWrong image name or registry authCheck image name, tags, and pull secrets
Permission deniedInit container runs as non-root but needs rootUse securityContext.runAsUser: 0 if appropriate

CKA Exam Patterns

# Quickly check init container status
kubectl get pod my-pod -o jsonpath='{range .status.initContainerStatuses[*]}{.name}{"\t"}{.state}{"\n"}{end}'
 
# Create a Pod with an init container from an existing deployment
kubectl run my-pod --image=nginx --restart=Never --dry-run=client -o yaml > pod.yaml
# Then manually add spec.initContainers section

Exam Tip: If a Pod is stuck and you suspect an init container, always check kubectl describe pod first. The Init Containers section shows exactly which init container is running or failed. Source: CKA Day 11

Practical Practice

Exam-style hands-on tasks for this topic. Complete each task before reviewing the solution. Time yourself — CKA tasks average 5–7 minutes.

Task 1: Init Container Creating Shared Data You are asked to create a Job named init-data-job where an init container writes a file /shared/data.txt with content “hello”, and the main container reads and outputs that file. Requirements: Use an emptyDir volume mounted at /shared in both containers. Verification: kubectl logs job/init-data-job shows “hello”. Solution:

apiVersion: batch/v1
kind: Job
metadata:
  name: init-data-job
spec:
  template:
    spec:
      initContainers:
      - name: init-writer
        image: busybox
        command: ['sh', '-c', 'echo hello > /shared/data.txt']
        volumeMounts:
        - name: shared
          mountPath: /shared
      containers:
      - name: main-reader
        image: busybox
        command: ['sh', '-c', 'cat /shared/data.txt']
        volumeMounts:
        - name: shared
          mountPath: /shared
      volumes:
      - name: shared
        emptyDir: {}
      restartPolicy: OnFailure

Task 2: Debug an Init Container Failure A Pod has an init container stuck in Init:Error. Find the failing init container, inspect its logs, and fix the command so it exits 0. Requirements: Do not delete the Pod. Identify the bad command from logs and edit the Pod manifest. Verification: kubectl get pod <pod> reaches Running status. Solution:

kubectl get pod <pod> -o jsonpath='{.status.initContainerStatuses[*].state}'
kubectl logs <pod> -c <init-container-name>
# Fix the command in the manifest and re-apply with --force

Task 3: Init Container Validating ConfigMap You are asked to create a Pod where the init container validates that a ConfigMap named app-config exists in the current namespace before the main app container starts. Requirements: The init container uses kubectl (image bitnami/kubectl) to query the ConfigMap. Verification: kubectl get pod config-check reaches Running only after the ConfigMap exists. Solution:

apiVersion: v1
kind: Pod
metadata:
  name: config-check
spec:
  initContainers:
  - name: check-config
    image: bitnami/kubectl:latest
    command: ['sh', '-c', 'kubectl get configmap app-config || exit 1']
  containers:
  - name: app
    image: nginx

Tags: kubernetes init-container pod troubleshooting cka devops initialization