Kubernetes Init Containers: Explained and Guide to Create One

In this blog, we will learn about a basic understanding of Kubernetes Init Container and how to create an Init Container on Kubernetes.

What is Init Containers?

Init containers are containers that start and run before the main container of the pod starts running. Init containers run tasks that are required for the main container to run.

For example, if you have a Java application running in a pod, the purpose of the init containers is to set up the pod for the application to run like configuring the required dependencies for the Java application.

For more clarification imagine you bought an unfurnished apartment before moving into the apartment your initial task is to clean the apartment and set furniture.

Just like how you won’t move into your apartment without cleaning or installing the furniture, the main container wouldn’t be able to run the application without the proper environment set by init containers.

How to Create Init Containers

First, create a manifest file init.yaml and copy the content given below

apiVersion: v1
kind: Pod
metadata:
  name: nginx
spec:
  initContainers:
  - name: init-container
    image: busybox
    command: ['sh', '-c', 'echo "Simple Init Container Example" > /nginx-init/index.html']
    volumeMounts:
    - name: nginx-config
      mountPath: /nginx-init
  containers:
  - name: main-container
    image: nginx:latest
    volumeMounts:
    - name: nginx-config
      mountPath: /usr/share/nginx/html
  volumes:
  - name: nginx-config
    emptyDir: {}

This file creates a pod nginx on the default namespace.

Once the pod has been created the init container echos the command to the index.html file.

When the init container completes its task, the main container which has the nginx web server image runs the Nginx web server with the file index.html and shows the content on its web page.

Run the following command to deploy the pod

kubectl apply -f init.yaml

Once you run the command you can see the pod runs the init container first and then runs the Nginx container as shown below

Init containers status check

Now the nginx pod is running, check if the pod uses the customized index.html file using port forwarding.

Run the following command to do port forwarding

kubectl port-forward pod/mypod 8080:80

You will get the following output on localhost:8080

nginx webpage

Conclusion

In summary, we have learned about init containers and how to create one.

I believe this blog gives you a basic understanding of init containers.

Other Interesting Blogs

Leave a Comment

Share via
Copy link
Powered by Social Snap