Init containers
- Version
- 1.37
- Review
- Draft
Summary#
Regular init containers run in order and each must exit successfully before the next can start. Kubernetes starts the app containers after initialization finishes. Use an init container to prepare files or perform a prerequisite check.
Syntax#
Put setup commands under spec.initContainers. To pass files to the app, mount the same volume in both containers.
kubectl logs POD -c INIT_CONTAINER
kubectl get pod POD -o jsonpath='{.status.initContainerStatuses[*].state}'
Example#
The init container writes a file to an emptyDir. The main container reads it and exits.
(
set -eu
ns="ref-init-$$"
kubectl create namespace "$ns" >/dev/null
trap 'kubectl delete namespace "$ns" >/dev/null' EXIT
kubectl wait -n "$ns" --for=create serviceaccount/default --timeout=60s >/dev/null
kubectl apply -n "$ns" -f - <<'YAML'
apiVersion: v1
kind: Pod
metadata:
name: report
spec:
restartPolicy: Never
initContainers:
- name: prepare
image: busybox:1.37
command: ["sh", "-ec", "echo 'report is ready' > /shared/report"]
volumeMounts:
- name: files
mountPath: /shared
containers:
- name: print
image: busybox:1.37
command: ["cat", "/shared/report"]
volumeMounts:
- name: files
mountPath: /shared
volumes:
- name: files
emptyDir: {}
YAML
kubectl wait -n "$ns" --for=jsonpath='{.status.phase}'=Succeeded pod/report --timeout=120s >/dev/null
kubectl get -n "$ns" pod report -o jsonpath='init exit={.status.initContainerStatuses[0].state.terminated.exitCode}{"\n"}'
kubectl logs -n "$ns" report -c print
)
Expected output#
pod/report created
init exit=0
report is ready
Common mistakes#
Make initialization safe to repeat. A retry can see files left by a previous attempt in the shared volume. For a Pod stuck initializing, use kubectl describe pod POD and read the failing init container's logs.
Version applicability#
The example uses the core v1 API on Kubernetes 1.37. A native sidecar uses restartPolicy: Always on an item in initContainers and can keep running alongside the app. That feature is stable since 1.33.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0