kubernetes: Adding initContainers to a pod

2 min read | by Jordi Prats

When setting up a pod we might need to populate some shared storage or generate some configuration files to be used for the actual containers that are going to run on that pod. It might not make sense that some tools just required for the setting up the environment to be available on the final container. Futhermore, we might need to run some scripts with higher privileges than we really need for running the pod. The initContainers come handy for covering this use-cases.

We can add init containers using spec.initContainers on the same way we use spec.containers. For example:

apiVersion: v1
kind: Pod
  name: my-pod
  - name: my-init
    image: demo
  - name: webserver
    image: nginx

There are some considerations though:

  • Init containers are not supposed be running as a background task: Will block the main containers deployment meanwhile they are running.
  • Each init container run sequentially and it must complete successfully before the next one starts.

If we use --watch with kubectl get pods we can see how this works:

$ kubectl get pods --watch
NAME                          READY   STATUS            RESTARTS   AGE
pet2cattle-8475d6697-jbmsm    0/1     Pending           0          0s
pet2cattle-8475d6697-jbmsm    0/1     Pending           0          0s
pet2cattle-8475d6697-jbmsm    0/1     Init:0/4          0          0s
pet2cattle-8475d6697-2sk4m    0/1     Init:1/4          0          4s
pet2cattle-8475d6697-2sk4m    0/1     Init:2/4          0          5s
pet2cattle-8475d6697-2sk4m    0/1     Init:2/4          0          6s
pet2cattle-8475d6697-2sk4m    0/1     Init:3/4          0          7s
pet2cattle-8475d6697-2sk4m    0/1     PodInitializing   0          8s
pet2cattle-8475d6697-2sk4m    0/1     Running           0          9s
pet2cattle-8475d6697-2sk4m    0/1     Running           0          41s
pet2cattle-8475d6697-2sk4m    1/1     Running           0          2m20s

Posted on 27/04/2021