Skip to main content

Init Containers and Multi Containers

Multi Containers

As we know, a pod can have more than one container.

Containers in a pod share the same network, the same declared volumes, and all things defined in spec.

They are born together and die together. Containers in a pod are scaled together and the service points to the pod, with each container listening on a specific port of the pod. Thus, a service can point to the ports of both containers.

As mentioned earlier, a pod should run its main application in one container, but often needs other containers alongside to help with certain things without mixing application functionalities.

These containers are called sidecars.

They are commonly used, for example, to send application logs to a specific location, but they have other functionalities that are better defined in the CKAD course.

These containers are expected to always be alive to keep the pod alive.

If any of the containers fail, the pod will restart.

Init Containers

Sometimes we only need to run a process that must be completed in a container, such as pulling code or a binary to be used by the main application. After finishing the pull, the container will stop and not stay alive, and the pod will keep restarting.

In this case, we use init containers.

Init containers run processes before the containers start and only run once during pod creation. Init containers must complete their task before the containers can start.

If any init container fails its task, Kubernetes will keep restarting the pod repeatedly until all init containers are successfully started.

Therefore, init container processes need to terminate instead of having a process that keeps them alive like in standard containers.

This is commonly used for application bootstrapping.

apiVersion: v1
kind: Pod
metadata:
name: myapp-pod
labels:
app: myapp
spec:
# This is the application container
containers:
- name: myapp-container
image: alpine
command: ['echo', 'The app is running', '&&','sleep 3600']
# These are the containers that need to start before the application.
initContainers:
- name: init-myservice
image: busybox
command: ['sleep', "30"]
# Simulation of a second process
- name: init-mydb
image: busybox
command: ['sleep', '60']

It wouldn't make sense to start the application if it depends on another and we need to ensure the service is available, so we use two containers to perform the checks.

Init containers DO NOT EXECUTE IN PARALLEL, but SEQUENTIALLY. One finishes first before the other starts.

If we have a sequence of two containers, one with sleep 30 and another with sleep 60, we would first wait 30 seconds and then 60 seconds, totaling 90 seconds.

Another curiosity is that when pods show 2/2 or 3/3, they represent containers and not init containers. They are not added to the container count.