Kubernetes Init Containers - Complete Guide & Examples

Comprehensive guide to Kubernetes Init Containers covering key features, execution patterns, YAML configuration examples, common use cases (service dependencies, secret management, database setup), and execution flow. Learn how init containers run before main application containers and must complete successfully.

Init Containers

Init containers are specialized containers that run before app containers in a Pod. They can contain utilities or setup scripts not present in the app image.

Key Features

Execution Pattern

  • Always run to completion
  • Each init container must complete successfully before the next one starts
  • If it fails, the kubelet repeatedly restarts it until it succeeds
  • Unless its restartPolicy is set to Never

Limitations

  • Probes are not supported
  • livenessProbe, readinessProbe, or startupProbe

Example Configuration

apiVersion: v1
kind: Pod
metadata:
    name: myapp-pod
    labels:
        app: myapp
spec:
    containers:
    - name: myapp-container
      image: busybox
      command: ['sh', '-c', 'echo The app is running! && sleep 3600']
    initContainers:
    - name: init-myservice
      image: busybox:1.28
      command: ['sh', '-c', "until nslookup mysvc.namespace.svc.cluster.local; do echo waiting for myservice; sleep 2; done"]
    - name: init-mydb
      image: busybox:1.28
      command: ['sh', '-c', "until nslookup mydb.namespace.svc.cluster.local; do echo waiting for mydb; sleep 2; done"]

Common Use Cases

Service Dependencies

Wait for other services to be available before starting the main application.

Secret Management

Fetch secrets or configuration data from external sources before the app starts.

Database Setup

Run database migrations or schema updates before the application starts.

Execution Flow

1

Init Container 1 runs

2

Init Container 2 runs

Main containers start

All init containers must complete successfully before the main application containers start.