Skip to main content
< All Topics

Kubernetes Pod Init Containers

In Kubernetes, InitContainers are specialized containers that run before your application starts. While your main application containers might run in parallel, InitContainers run sequentially and must complete successfully before the main application is even allowed to start.

Does not support probs and lifecycle

Why Use InitContainers?

There are two primary reasons to use them: Dependencies and Security.

1. Waiting for Dependencies (The “Blocker”)

Modern distributed apps are race conditions waiting to happen. If your App starts before your Database is ready, your App crashes.

  • The Problem: Kubernetes starts Pods fast. Databases take time to load.
  • The Solution: An InitContainer runs a script that repeatedly checks “Is the DB there?” It blocks the main app from starting until the answer is “Yes.”
2. Security Setup (The “Root” Trick)

For security, you want your Main App to run as a Non-Root user (least privilege). However, sometimes you need to do things that require Root, like:

  • Changing kernel settings (sysctl).
  • Fixing file permissions on a mounted volume.

The Strategy:

  1. InitContainer (Runs as Root): Mounts the volume, runs chown or sysctl to set things up, and then terminates.
  2. Main Container (Runs as Non-Root): Starts up and uses the volume/settings that are now correctly configured.
FeatureInitContainersNormal (Main) Containers
ExecutionSequential (one at a time)Parallel
LifecycleRuns to completion (must exit 0)Runs indefinitely (Daemon/Server)
FailurePod restarts (Standard)Restart policy applies
ProbesNo Readiness/Liveness probesSupports all probes
Best Practices
  • Keep them small: Use lightweight images like alpine or busybox to ensure the Pod starts quickly.
  • Idempotency: An InitContainer might run multiple times (e.g., if the Pod restarts). Ensure your script handles running twice without breaking things.
  • Log clearly: Use echo commands in your scripts (e.g., echo "Waiting for DB..."). If the Pod is stuck in Init:CrashLoopBackOff, these logs are the only way to debug what went wrong.


Contents
Scroll to Top