Skip to content
Latchkey

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

Run this faster and cheaper on Latchkey managed runners. Start free →