How do you run database migrations safely during a Kubernetes deployment?
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)
- Expand — add the new column (nullable), deploy code that writes both old and new.
- Migrate data in the background.
- Deploy code that reads only the new column.
- 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."