How to Create Init Containers on Kubernetes Cluster

In this blog, we are going to look at the Init containers of the Kubernetes cluster.

We often arrange multiple containers in one Pod for better communication such as collecting logs, collecting metrics, etc.

But we know that the main container can work without the help of these Sidecar containers.

Even though, some containers are necessary to run before launching the main container. For example, dependencies check or secrets placed in the main container.

We can clearly say that these containers don’t need to be run all the time but to initialize the main container.

Let’s do a simple hands-on.

If you curl the Nginx Pod with default configuration, you will get this same output.

image 10

I want to change it when the runtime of the Pod.

Create a Manifest with an Init Container

I am creating a Busybox init container along with a Nginx container.

The Init container will create a new index.html file and this file will be placed in the /usr/share/nginx directory of the Nginx container.

cat << EOF > init-container.yaml
apiVersion: v1
kind: Pod
  name: nginx-with-init-container
    - name: nginx
      image: nginx:latest
        - name: config-volume
          mountPath: /usr/share/nginx/html
    - name: init-config
      image: busybox:latest
      command: ['sh', '-c', 'echo "This is the modified index.html by init container" > /config/index.html']
        - name: config-volume
          mountPath: /config
    - name: config-volume
      emptyDir: {}

Both containers and initContainers will be placed under the spec section.

Here is the main thing you have to notice is that the volumes, both containers share the same volume.

The Init containers will run first and only after the completion of its task, the main containers will be launched.

image 12

As with regular containers, we can add more than one Init container on a Pod and they will be run one by one.

We can add a parameter with the Init container which is restartPolicy, to change the behaviour of the Init container.

Always will not let the Init container be removed, the container keeps restarting even if the job is completed.

OnFailure will also restart the Init container when it fails to finish its job.

Never is the default one, and in this, if the container successfully completes the job, then it will be removed.

kubectl describe pod nginx-with-init-container
image 13


The Init containers are for doing a special operation on the main container so keeping them simple is a good practice, this is the high-level overview of the Init containers, you can do more with these containers based on your requirements.

Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like