How to Run Database Migrations Before a Deploy in Jenkins
A migration stage that precedes deploy fails the pipeline before the new code ships if the schema change breaks.
Put migrations in their own stage ahead of deploy. The deploy stage only runs when migrations pass, so code never ships against an unmigrated schema.
Steps
- Bind the database credential for the migration tool.
- Run migrations in a stage before deploy.
- Let the deploy stage run only after migrations succeed.
Pipeline
Jenkinsfile
pipeline {
agent any
environment { DATABASE_URL = credentials('prod-db-url') }
stages {
stage('Migrate') {
steps { sh 'npx prisma migrate deploy' }
}
stage('Deploy') {
steps { sh './deploy.sh' }
}
}
}Gotchas
- Write backward-compatible migrations so the old code keeps working during the rollout.
- A failed migration stops the pipeline before deploy, which is the safe default.
Related guides
How to Gate a Production Deploy With Input and Timeout in JenkinsGate a production deploy in Jenkins behind a manual approval that auto-aborts after a timeout, wrapping the i…
How to Promote a Build Between Environments in JenkinsPromote the exact artifact that passed staging to production in Jenkins by reusing the same build identifier…