helm, kubernetes

InitContainers in Kubernetes


Init containers

Sometimes in kubernetes ,one container in Pod wait for another container due to several reasons .

For instance , Pod is waiting for
1 Another pod service to come up
2 Initialising the database
3 Loading heavy application .

During this time, if you connect the pod ,it will fail with error. Even If you put a delay in pod ,it won’t be ideal solution for this problem .Today we are going to discuss, how to solve this problem using init container .

In my case ,I have server pod which is running the service and my slave pod is waiting for the service to consume . Suppose the slave pod connects earlier, then it will fail with error.

Now I have to add a check that, my slave pod will connect to master pod whenever master service is up and running otherwise it should wait ..

Before implementing this, I have written the script in the master pod “if service is running then return the service otherwise wait for the service “. If the script is working fine then we are going to add this snippet in to Init containers in command section,

Script content :

service=`ps -ef | grep -i <your-service name > |
grep -v grep  | wc -l` ; 
echo $service; 
until [[ $service < 1 ]]; 
do echo waiting for service; 
sleep 2; 
done;

InitContainers :
-name : name of your pod service
image : image where your service is running
command : set ‘bin/bash’ /’sh’ depends on your container shell
-c command line
<script content > script to run [Replace with above script ]

deployment file :

   
initContainers:
  - name: master-service
    image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
    command: ['/bin/bash', '-c', '<script content >']
containers:
  - name: {{ .Chart.Name }}
        

I hope you understand this .Let me know if you have any questions ..

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.