Node.js › Docker & Deployment
How do you handle running database migrations as part of a Kubernetes-based Node.js deployment pipeline?
AdvancedAnswer
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: NeverReal-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.