Back to results for “Deployment”
Node.js › Docker & Deployment

How do you handle running database migrations as part of a Kubernetes-based Node.js deployment pipeline?

Advanced

Answer

Running migrations requires care in an environment with multiple replicas, since running the same migration concurrently from every new pod could cause conflicts or duplicate work -- a common pattern uses a Kubernetes Job (a separate, one-off pod that runs to completion rather than staying alive) to run migrations exactly once as a distinct pre-deployment step, only proceeding to roll out the new application pods after the migration Job completes successfully.
apiVersion: batch/v1
kind: Job
metadata: { name: db-migrate }
spec:
  template:
    spec:
      containers:
      - name: migrate
        image: myapp:v1.2.3
        command: ['npm', 'run', 'migrate']
      restartPolicy: Never
Real-world example A CI/CD pipeline runs a Kubernetes Job to apply pending database migrations and waits for it to report success before triggering the actual rolling update of the application deployment, ensuring the new code never runs against a database schema it doesn't yet expect.

Common follow-ups: What happens if the migration Job fails -- how should the pipeline handle that before proceeding with the application deployment?;How do you handle a migration that must remain backward-compatible with the still-running old version of the application during a rolling update?