patternbashkubernetesTip
Init containers for dependency ordering and one-time setup
Viewed 0 times
init containerdependency orderingstartup sequencewait-fordatabase migrationpre-startncnetcat
Problem
An application container starts before its dependencies (database, config service) are ready, causing startup failures. Using sleep hacks in the main container entrypoint is fragile.
Solution
Use init containers to run prerequisite checks or setup tasks before the main container starts. Init containers run to completion in sequence before any app containers start.
initContainers:
- name: wait-for-db
image: busybox
command: ['sh', '-c', 'until nc -z postgres-service 5432; do echo waiting; sleep 2; done']
- name: run-migrations
image: myapp:latest
command: ['python', 'manage.py', 'migrate']
env:
- name: DATABASE_URL
valueFrom:
secretKeyRef:
name: db-secret
key: urlWhy
Init containers are a first-class Kubernetes concept for sequencing startup logic. They have their own image and security context, run to completion, and are retried until they succeed. Only when all init containers succeed do app containers start.
Gotchas
- Init containers restart from the beginning if they fail — make sure they are idempotent
- Init containers share the pod's volumes and network — useful for pre-populating data directories
- All init containers run sequentially, not in parallel
- Init container images are not automatically updated when the app container image changes — version them separately
- Long-running init containers delay pod readiness and can cause issues with liveness probe timeouts
Code Snippets
Debug a stuck init container
# Check init container logs when pod is stuck in Init:0/1
kubectl logs <pod-name> -c wait-for-db
kubectl describe pod <pod-name> | grep -A 10 'Init Containers'Context
Orchestrating startup dependencies between services within a pod
Revisions (0)
No revisions yet.