Kubernetes init containers

Published On: 2019/12/23

How do we ensure that external services/resources are running or ready before starting the application? Or prepare something which is required to successfuly run the application. The Init Container provides a way to handle these cases.

An Init container is configured in the Pod at the same level as of containers.

apiVersion: v1
kind: Pod
metadata:
  name: myapp
spec:
  containers:
  - name: main
    image: busybox
    command: ['sh', '-c', 'echo check the file >> /tmp/app_path/test/1.txt && sleep 3600']
    volumeMounts:
    - name: local-vol
      mountPath: /tmp/app_path
  initContainers:
  - name: init-box
    image: busybox
    command: ['mkdir', '/tmp/app_path/test']
    volumeMounts:
    - name: local-vol
      mountPath: /tmp/app_path
  volumes:
  - name: local-vol
    hostPath:
      path: /tmp/app/main

The above Pod configuration is created to start a pod with with one container and an init container. The init container command creates a directory in the pod which can be accessable by the main container. The init containers complete the task of create the directory and exits and then the main container will be initialized.

The output of the above configuration is as given below.

Events:
  Type    Reason     Age   From                 Message
  ----    ------     ----  ----                 -------
  Normal  Scheduled  10s   default-scheduler    Successfully assigned default/myapp to node01
  Normal  Pulling    9s    kubelet, node01      Pulling image "busybox"
  Normal  Pulled     7s    kubelet, node01      Successfully pulled image "busybox"
  Normal  Created    7s    kubelet, node01      Created container init-box
  Normal  Started    7s    kubelet, node01      Started container init-box
  Normal  Pulling    7s    kubelet, node01      Pulling image "busybox"
  Normal  Pulled     6s    kubelet, node01      Successfully pulled image "busybox"
  Normal  Created    6s    kubelet, node01      Created container main
  Normal  Started    5s    kubelet, node01      Started container main

Conclusion

The init container could be considered as a tool to prepare the required resources which could be used by the main container/s of a given Pod.

comments powered by Disqus