Configuring Init Containers
1. Understanding Init Container Purpose
| Property | Behavior |
| Order | Run sequentially before app containers |
| Must succeed | Each must complete (exit 0); else Pod restarts |
| No probes | Liveness/readiness not applicable |
| Use cases | Wait for dependencies, fetch config, run migrations, set up filesystem |
2. Defining Init Containers
Example: Wait for database
spec:
initContainers:
- name: wait-db
image: busybox:1.36
command: ["sh","-c","until nc -z db 5432; do sleep 1; done"]
containers:
- name: app
image: myapp:1.0
3. Setting Init Container Order
| Rule | Detail |
| Sequential | Defined list order = execution order |
| Failure | Restart per Pod restartPolicy; back-off doubles |
| Resources | Effective request = max(initContainers, sum(appContainers)) |
4. Sharing Volumes with Main Containers
Example: Init writes, app reads
volumes:
- name: shared
emptyDir: {}
initContainers:
- name: fetch
image: curlimages/curl
command: ["sh","-c","curl -o /data/config.json https://cfg/svc"]
volumeMounts: [{ name: shared, mountPath: /data }]
containers:
- name: app
image: myapp
volumeMounts: [{ name: shared, mountPath: /etc/app }]
| Volume Type | Use |
| emptyDir | Most common for handoff |
| PVC | Persist across pod restarts |
5. Setting Init Container Resources
| Field | Note |
| requests/limits | Same fields as app containers |
| Effective Pod request | max(highest init, sum(app)) |
6. Handling Init Container Failures
| restartPolicy | Failure Behavior |
| Always / OnFailure | Restart failed init container (back-off) |
| Never | Pod marked Failed |
kubectl describe pod <pod> # Init Containers section shows reason
kubectl logs <pod> -c <init-name>
7. Debugging Init Containers
| Command | Purpose |
kubectl logs POD -c INIT | View init logs |
kubectl logs POD -c INIT --previous | Logs from prior attempt |
kubectl describe pod POD | Status, reason, last state |
8. Using Init Containers for Dependencies
initContainers:
- name: wait-redis
image: busybox
command: ["sh","-c","until nslookup redis; do sleep 2; done"]
- name: wait-api
image: curlimages/curl
command: ["sh","-c","until curl -sf http://api/health; do sleep 2; done"]
| Pattern | Probe |
| DNS check | nslookup service |
| TCP check | nc -z host port |
| HTTP check | curl -sf URL/health |
9. Running Database Migrations
Example: Flyway migration init
initContainers:
- name: migrate
image: flyway/flyway:10
args: ["-url=jdbc:postgresql://db/app","-user=app","migrate"]
env:
- name: FLYWAY_PASSWORD
valueFrom: { secretKeyRef: { name: db, key: password } }
Note: Per-pod migrations run on every replica restart. For one-shot migrations prefer a Job gated by a Helm hook or Argo sync wave.
10. Downloading Configuration Files
| Source | Init Image |
| HTTP/S | curlimages/curl |
| Git | alpine/git |
| Vault | vault + vault kv get |
| AWS S3 | amazon/aws-cli |