Init container¶
An Init container is a specialized container in a Kubernetes Pod that runs before the main application containers start.^[400-devops-06-kubernetes-k8s-ithelp-day10-readme.md]
Behavior and Execution¶
Init containers are used to perform initialization logic or setup tasks that must complete successfully before the main containers launch.^[400-devops-06-kubernetes-k8s-ithelp-day10-readme.md] A Pod can contain one or multiple Init containers. If there are multiple, they are executed sequentially in the order they are defined in the Pod specification; each must complete successfully before the next one begins.^[400-devops-06-kubernetes-k8s-ithelp-day10-readme.md]
This design separates initialization logic from the main application logic, allowing the main containers to focus solely on runtime concerns while the Init containers handle prerequisites.^[400-devops-06-kubernetes-k8s-ithelp-day10-readme.md]
Common Use Cases¶
Init containers are typically employed to ensure dependencies or environmental requirements are met prior to the application starting:
- Waiting for dependencies: They can be used to block the start of a main container until a dependent service (such as a database) is ready.^[400-devops-06-kubernetes-k8s-ithelp-day10-readme.md]
- Configuration and setup: They can perform initial setup tasks, such as detecting cluster members or generating configuration files required by the main application.^[400-devops-06-kubernetes-k8s-ithelp-day10-readme.md]
Data Sharing¶
Init containers share the same Pod environment as the application containers. They can access the same [[Volumes]] and Network Namespace, allowing them to pass data or configuration files generated during initialization to the main containers.^[400-devops-06-kubernetes-k8s-ithelp-day10-readme.md]
In the example below, an init container downloads a file into a shared emptyDir volume. Once the init container finishes, the main nginx container starts and serves the file from that shared volume^[400-devops-06-kubernetes-k8s-ithelp-day10-readme.md]:
apiVersion: v1
kind: [Pod](<./pod.md>)
metadata:
name: init-demo
spec:
volumes:
- name: workdir
emptyDir: {}
initContainers:
- name: install
image: busybox
command:
- wget
- "-O"
- "/work-dir/index.html"
- http://www.baidu.com
volumeMounts:
- name: workdir
mountPath: "/work-dir"
containers:
- name: nginx
image: nginx
ports:
- containerPort: 80
volumeMounts:
- name: workdir
mountPath: /usr/share/nginx/html
Sources¶
^[400-devops-06-kubernetes-k8s-ithelp-day10-readme.md]