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:
- InitContainer (Runs as Root): Mounts the volume, runs
chownorsysctlto set things up, and then terminates. - Main Container (Runs as Non-Root): Starts up and uses the volume/settings that are now correctly configured.
| Feature | InitContainers | Normal (Main) Containers |
| Execution | Sequential (one at a time) | Parallel |
| Lifecycle | Runs to completion (must exit 0) | Runs indefinitely (Daemon/Server) |
| Failure | Pod restarts (Standard) | Restart policy applies |
| Probes | No Readiness/Liveness probes | Supports all probes |
Best Practices
- Keep them small: Use lightweight images like
alpineorbusyboxto 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
echocommands in your scripts (e.g.,echo "Waiting for DB..."). If the Pod is stuck inInit:CrashLoopBackOff, these logs are the only way to debug what went wrong.