Some work has to happen before the app may start: wait for the database, write a config file, fetch a dataset. That is what init containers are for.
initContainers[0] wait-for-dbruns, must exit 0
initContainers[1] prepare-filesthen runs, must exit 0
containers[*] apistart together, only now
yaml
spec:
initContainers:
- name: wait-for-db
image: busybox
command: ["sh", "-c", "until nc -z market-db 5432; do echo waiting; sleep 2; done"]
containers:
- name: api
image: stackmonsters/monster-market-apiThe same block goes under spec.template.spec in a Deployment.
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.
What you see
text
learner@shallows:~$ 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 none of one init containers has finished. Init:Error and Init:CrashLoopBackOff mean one keeps failing. describe pod has an Init Containers: section with the same detail as Containers:, and -c reads an init container's logs:
text
learner@shallows:~$ kubectl logs market-api -c wait-for-db
waiting| Need | Init container does |
|---|---|
| The database must be up before the API starts | Loop on nc -z market-db 5432 |
| A config file must be rendered | Write it to a shared emptyDir |
| A file the image lacks | wget it into a shared volume |