A Pod can list containers that run before the app containers. They are called init containers.
text
Pod start
│
├─ initContainers[0] wait-for-db runs ─▶ exit 0
├─ initContainers[1] migrate runs ─▶ exit 0
│
└─ containers[*] api start (all at once)Rules:
- They run one at a time, in order.
- Each must exit 0. On failure it is retried with backoff and the app containers do not start.
- They share the Pod's volumes and network, so they can write files the app reads, or check that a Service answers.
The manifest
yaml
apiVersion: v1
kind: Pod
metadata:
name: market-api
spec:
initContainers:
- name: wait-for-db
image: busybox
command: ["sh", "-c", "until nc -z market-db 5432; do sleep 2; done"]
containers:
- name: api
image: stackmonsters/monster-market-apiThe same block goes under spec.template.spec in a Deployment.
What you see
console
$ kubectl get pods
NAME READY STATUS RESTARTS AGE
market-api 0/1 Init:0/1 0 4s
market-api 0/1 PodInitializing 0 9s
market-api 1/1 Running 0 12sInit:0/1 means zero of one init containers has finished. PodInitializing is the moment between the last init container and the app containers.
Logs of an init container are read with -c:
console
$ kubectl logs market-api -c wait-for-dbWhen to use one
| Need | Init container does |
|---|---|
| The database must be up before the API starts | Loop on nc -z db 5432 |
| A schema migration must run once per rollout | Run the migration, exit 0 |
| A config file must be rendered from a template | Write it to a shared emptyDir volume |
| Fetch a file the image does not contain | wget into a shared volume |
The sandbox cluster in this course runs init containers as ordinary containers, so this topic has no lab here. The Jobs lab next uses the same "run to completion" idea at the Pod level.