Kuberneteskubernetesinit-containersstartupmigrationsproduction-ready
Init Containers Pattern
Kubernetes init containers for database migrations, config loading, dependency waiting, and secret provisioning before app startup.
title: "Init Containers Pattern" description: "Kubernetes init containers for database migrations, config loading, dependency waiting, and secret provisioning before app startup." category: "Kubernetes" language: "yaml" tags: ["kubernetes", "init-containers", "startup", "migrations", "production-ready"] createdAt: "2025-02-22" updatedAt: "2025-03-12"
Overview
Init containers establish preconditions before the main application starts: waiting for dependencies, running migrations, fetching configuration, and warming caches. They run sequentially, and the pod only starts when all succeed.
Code
initContainers:
- name: wait-for-db
image: busybox
command: ['sh', '-c', 'until nc -z db 5432; do sleep 2; done']
- name: migrate
image: myapp
command: ['node', 'migrate.js']Notes
- Init containers run in order; each must complete successfully before the next starts
- If any init container fails, Kubernetes restarts the pod (with backoff)
- Use lightweight images (
busybox,curl) for utility init containers to reduce pull time - Shared volumes (
emptyDir) pass data from init containers to the main container - Migration containers should be idempotent (safe to re-run on pod restart)
- Service account token projection provides short-lived tokens for secure API access