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

  1. Init container runs to completion.
  2. Main container starts only after all init containers exit with code 0.
  3. 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.
  4. Only side effects (indexes created, migrations applied) persist.

See also