How do you handle special pod startup needs with initContainers?

Kubernetes initContainers run when a pod is first initialized. Their job is to run bootstrapping tasks before a pod’s primary application container runs. InitContainers are great for separating preparation steps from operations. They run in sequence, each one completing their assigned task before the next initContainer or any application container runs. If any of them fail, Kubernetes considers the pod unhealthy and attempts to restart the pod’s containers (including the initContainers) according to the Pod’s restartPolicy setting.

Using Kubernetes initContainers has many benefits, some of our favorites are:

  • Leaner application images – all preparation steps are executed in separate, and potentially reusable, containers, offloading utilities that would only be used on boot by the application container anyway
  • Easier to spot failures –  initContainer logs are stored separately from app container logs; if the bootstrapping activity was done by the application container in, for example, a “docker-entrypoint.sh” script, you would need to debug the entire script! With initContainers, you can simply list logs from the container to see what’s going wrong
  • Fewer instances of unprepared or half-running app containers – the main application only starts when initContainer preparations complete successfully. If any of the initContainers fail to prepare the pod for app execution, the application never starts.
  • Security boundaries – privileged system calls can be made by initContainers during bootstrapping and restricted at application runtime

In this quick video, we show two ways Kubernetes initContainers support app containers within a pod:

Init C1 pulls a generic config file template from a Git repository, renders the template with live values from its environment and saves it to a shared volume.

Init C2 runs a process that retrieves a backup snapshot from an object store, unpacks it, and places it in a persistent volume so that the new pod can pick up where an old one left off.

When the primary application container comes up it mounts to the shared volume to retrieve the template rendered by Init C1 and mounts the persistent volume to initialize itself from the backup prepared by Init C2.

Secret Link