Skip to content

Init containers

Init containers are specialized containers that run before the main application containers in a Pod start.^[400-devops__06-Kubernetes__k8s-ithelp__Day10__README.md] They serve to perform initialization logic or setup tasks, ensuring that the environment is fully prepared before the main application processes begin.^[400-devops__06-Kubernetes__k8s-ithelp__Day10__README.md]

Execution and Ordering

A Pod can contain one or more init containers.^[400-devops__06-Kubernetes__k8s-ithelp__Day10__README.md] If multiple init containers are defined, they are executed sequentially in the order they appear in the Pod's specification.^[400-devops__06-Kubernetes__k8s-ithelp__Day10__README.md] All init containers must complete successfully before the main containers are allowed to start.^[400-devops__06-Kubernetes__k8s-ithelp__Day10__README.md]

Because all containers within a Pod share the same Network Namespace and can access shared storage volumes, init containers can perform setup tasks—such as downloading configuration files or modifying network settings—that the main containers inherit upon startup.^[400-devops__06-Kubernetes__k8s-ithelp__Day10__README.md]

Use Cases

Init containers are primarily used to decouple initialization logic from the main application image, promoting flexibility and separation of concerns.^[400-devops__06-Kubernetes__k8s-ithelp__Day10__README.md] Common scenarios include:

  • Dependency Management: Waiting for other services (e.g., a database) to become ready before starting the main application.^[400-devops__06-Kubernetes__k8s-ithelp__Day10__README.md]
  • Configuration Preparation: Preparing configuration files or initializing data that the main application requires at runtime.^[400-devops__06-Kubernetes__k8s-ithelp__Day10__README.md]

Example

The following example demonstrates an Init container that downloads a file into a shared emptyDir volume. The main nginx container subsequently serves this file, illustrating how resources can be shared between the initialization phase and the application phase.^[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]