Pattern
Use an initContainer to run one-off setup scripts (DB migrations, index seeding) before the main container starts. The init container must exit cleanly before Kubernetes starts the main container — if it crashes, the pod stays in Init:CrashLoopBackOff.
initContainers:
- name: ensure-indexes
image: <ecr-image>
command: ["node", "dist/scripts/ensureIndexes.js"]
env:
- name: MONGO_URI
valueFrom:
secretKeyRef: ...Tip
Make scripts idempotent — initContainers run on every pod boot. Operations like
createIndexes()are safe because they no-op when the index already exists. Destructive operations are not.
Warning
Dirty data can cause init to fail — if the script enforces a constraint (e.g. a unique index) against a collection with pre-existing violations, the init container will fail and block the pod from starting. Verify data cleanliness before deploying to a new environment.
Lifecycle
- Init container runs to completion.
- Main container starts only after all init containers exit with code 0.
- Init container instance is discarded — no shared memory, no sidecar, no running process. The script itself persists in the image layer in ECR and is available on every subsequent pull.
- Only side effects (indexes created, migrations applied) persist.
See also
- pod-management — restarting and watching pod status
- typescript-compile-at-build-time — compiling TS scripts into the image so they can be run with plain
node