Skip to content

Init Containers

Overview

Init containers run before app containers start. They must complete successfully before the main container starts.


Key Characteristics

FeatureInit Container
Run orderSequential, before app containers
Must completeYes, must exit 0
Restart on failureYes, pod restarts
Share volumesYes, with app containers
Resource limitsCalculated separately

Use Cases

  • Wait for a service to be ready
  • Clone a git repo
  • Register with external service
  • Download/prepare configuration
  • Run database migrations

Basic Example

yaml
apiVersion: v1
kind: Pod
metadata:
  name: init-demo
spec:
  initContainers:
  - name: wait-for-service
    image: busybox:1.36
    command: ['sh', '-c', 'until nslookup myservice; do echo waiting; sleep 2; done']
  - name: init-data
    image: busybox:1.36
    command: ['sh', '-c', 'echo "initialized" > /data/ready']
    volumeMounts:
    - name: shared-data
      mountPath: /data
  containers:
  - name: app
    image: nginx
    volumeMounts:
    - name: shared-data
      mountPath: /usr/share/nginx/html
  volumes:
  - name: shared-data
    emptyDir: {}

Multiple Init Containers

Run in order - each must succeed before next starts:

yaml
spec:
  initContainers:
  - name: init-1    # Runs first
    image: busybox
    command: ['echo', 'step 1']
  - name: init-2    # Runs after init-1 completes
    image: busybox
    command: ['echo', 'step 2']
  - name: init-3    # Runs after init-2 completes
    image: busybox
    command: ['echo', 'step 3']

Wait for Service Example

yaml
initContainers:
- name: wait-for-db
  image: busybox:1.36
  command:
  - sh
  - -c
  - |
    until nc -z postgres-svc 5432; do
      echo "waiting for postgres..."
      sleep 2
    done

Clone Git Repo

yaml
initContainers:
- name: git-clone
  image: alpine/git
  command:
  - git
  - clone
  - https://github.com/example/repo.git
  - /app
  volumeMounts:
  - name: app-volume
    mountPath: /app

Check Init Container Status

bash
# See init container status
kubectl get pod <pod-name>

# STATUS shows init progress: Init:0/2, Init:1/2, PodInitializing, Running

# Describe for details
kubectl describe pod <pod-name>

# Logs from init container
kubectl logs <pod-name> -c <init-container-name>

Debugging Failed Init

bash
# Check which init failed
kubectl describe pod <pod-name> | grep -A10 "Init Containers"

# Get logs from failed init
kubectl logs <pod-name> -c <init-container-name>

# Check events
kubectl get events --field-selector involvedObject.name=<pod-name>

Released under the MIT License.