No, PM2’s pm2 deploy rollback cannot safely revert database migrations on its own. The command is designed to revert the application code to a previous git commit and restart the process; it has no native awareness of your database schema or the migration state.
The Gap Between Code and Schema
When you trigger a rollback, PM2 restores the previous version of the source code. However, if the failed deployment included a migration that added a column or changed a table structure, that change remains in the database. This creates a schema-code mismatch, which often leads to runtime crashes (e.g., Undefined column errors) because the reverted code expects the old schema while the database provides the new one.
Implementing Automated Migration Rollbacks
To synchronize these actions, you must leverage PM2's deployment hooks to trigger your migration tool's "down" or "rollback" commands. This assumes you are using a migration framework (such as Knex, Sequelize, or TypeORM) that supports reversible migrations.
Configuration Steps
- Define a Rollback Script: Ensure your
package.json or migration tool has a command to revert the last migration (e.g., npm run migrate:rollback).
- Configure the Deploy File: In your
ecosystem.config.js, use the post-deploy hook. When a rollback occurs, PM2 executes the post-deploy script of the version being rolled back to.
- Execution Flow:
- The rollback command is issued.
- PM2 switches the current symlink to the previous release.
- The
post-deploy script of that previous release is executed.
- The application is restarted.
// Example ecosystem.config.js snippet
module.exports = {
deploy: {
production: {
// ... other config
"post-deploy": "npm run migrate:rollback && npm install"
}
}
}
Verification and Safety
Before relying on this in production, verify the behavior in a staging environment using these steps:
- Deploy a version that creates a new table.
- Execute
pm2 deploy rollback production.
- Verify via your DB client that the table was dropped and the application is running the previous code version without errors.
Warning: Automated rollbacks can be destructive. If the new deployment has already written new data to the new schema, a migration rollback may result in permanent data loss.
Required Diagnostic Detail
To provide a more specific script recommendation, please specify which migration framework (e.g., Knex, Sequelize, TypeORM) you are using and whether your migrations are designed to be idempotent.