How do you run database migrations safely during a Kubernetes deployment?

IntermediateScenarioDatabase connections in apps
Answer

Short answer

Run migrations once, before the new app version rolls out — as a Kubernetes Job, a Helm pre-upgrade hook, an Argo CD PreSync hook or a pipeline step — using a dedicated migration DB user. And write backward-compatible migrations, because old and new pods run side by side during a rolling update.

Helm hook example

apiVersion: batch/v1
kind: Job
metadata:
  name: orders-migrate-{{ .Release.Revision }}
  annotations:
    "helm.sh/hook": pre-upgrade,pre-install
    "helm.sh/hook-delete-policy": before-hook-creation,hook-succeeded
spec:
  backoffLimit: 1
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: migrate
          image: registry/orders:{{ .Values.image.tag }}
          command: ["flyway", "migrate"]
          envFrom: [{ secretRef: { name: orders-migrator } }]

If the Job fails, the upgrade stops and the old version keeps running.

Expand / contract pattern (zero downtime)

  1. Expand — add the new column (nullable), deploy code that writes both old and new.
  2. Migrate data in the background.
  3. Deploy code that reads only the new column.
  4. Contract — drop the old column in a later release.

Never rename or drop something the currently running version still uses.

Why not run migrations at app startup?

It works for small apps, but with 10 replicas they all try at once (Flyway locks, but startup slows and failures crash-loop pods). A separate step is easier to control and observe.

What to say in the interview

"Migrations run once as a pre-upgrade Job or PreSync hook with a migration user; a failure stops the rollout. Every migration is backward-compatible using expand/contract, because during a rolling update old and new pods share the database."

All Build Tools (Java, Node.js, Python, .NET) questions Roadmap: Connecting apps to databases

More on Database connections in apps