61/100 Init Containers in Kubernetes

Init containers are a special type of container in K8's that run before the main (regular) application containers start inside a pod.  They are used for initialisation or setup tasks that need to happen once before the main app runs.

You can think of them as setup jobs that prepare the environment for the main container:
- Runs to completion before any app containers start.
- Runs sequentially — each one must finish successfully before the next starts.
- Is defined inside a Pod’s spec (just like regular containers).


There are some applications that need to be deployed on Kubernetes cluster and these apps have some pre-requisites where some configurations need to be changed before deploying the app container. Some of these changes cannot be made inside the images so the DevOps team has come up with a solution to use init containers to perform these tasks during deployment.

  1. Create a Deployment named as ic-deploy-devops.
  2. Configure spec as replicas should be 1, labels app should be ic-devops, template's metadata lables app should be the same ic-devops.
  3. The initContainers should be named as ic-msg-devops, use image fedora with latest tag and use command '/bin/bash', '-c' and 'echo Init Done - Welcome to xFusionCorp Industries > /ic/blog'. The volume mount should be named as ic-volume-devops and mount path should be /ic.
  4. Main container should be named as ic-main-devops, use image fedora with latest tag and use command '/bin/bash', '-c' and 'while true; do cat /ic/blog; sleep 5; done'. The volume mount should be named as ic-volume-devops and mount path should be /ic.
  5. Volume to be named as ic-volume-devops and it should be an emptyDir type.

Create the ic-deploy-devops.yaml file.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: ic-deploy-devops
spec:
  replicas: 1
  selector:
    matchLabels:
      app: ic-devops
  template:
    metadata:
      labels:
        app: ic-devops
    spec:
      initContainers:
        - name: ic-msg-devops
          image: fedora:latest
          command: ["/bin/bash", "-c", "echo Init Done - Welcome to xFusionCorp Industries > /ic/blog"]
          volumeMounts:
            - name: ic-volume-devops
              mountPath: /ic
      containers:
        - name: ic-main-devops
          image: fedora:latest
          command: ["/bin/bash", "-c", "while true; do cat /ic/blog; sleep 5; done"]
          volumeMounts:
            - name: ic-volume-devops
              mountPath: /ic
      volumes:
        - name: ic-volume-devops
          emptyDir: {}

Deploy: kubectl apply -f ic-deploy-devops.yaml

Verify its running: kubectl get pods