PM2 deploy revert does not roll back database schema after code rollback
0 reputation · 05 May 2020, 03:34 UTC
0 reputation · 05 May 2020, 03:34 UTC
When a deployment introduces a database schema change, the expectation is that rolling back the application code with pm2 deploy revert also returns the database to its previous compatible state.
However, the revert command only restores the released source code and Node modules; it does not automatically invoke any migration down scripts, and there is no documented post-revert hook to run them. Users must rely on existing post-deploy or custom scripts, but their execution during a revert is not guaranteed, which can leave the database in an incompatible state.
post-revert hook be introduced to ensure safe rollback of schema changes?No, PM2 does not provide a built-in mechanism to automatically run database "down" migrations during a revert. The pm2 deploy revert command is strictly limited to the application's file system—restoring the previous release folder and updating the current symlink. It has no integration with database state or migration history tables.
The discrepancy occurs because PM2 manages the deployment artifact (code and dependencies), whereas schema changes are persistent state managed by your database migration tool. When you revert code, the migration tool's history table (e.g., SequelizeMeta or flyway_schema_history) still records the newer migrations as "applied," leaving the database in a state that may be incompatible with the older code version.
To coordinate code and database rollbacks without manual risk, you must trigger your migration tool's undo functionality. Since PM2 lacks a native post-revert hook, you can implement a wrapper script or use a custom command to ensure both occur atomically.
# Sequelize
npx sequelize db:migrate:undo
# Knex
knex migrate:rollback
# Flyway
flyway undo
# Example for Sequelize
npx sequelize db:migrate:status
DROP COLUMN or DROP TABLE commands in down-migrations. If data was added during the failed deployment, a standard rollback may delete that data permanently.revert for databases entirely, instead deploying a new "fix-forward" migration that restores the previous schema state.Use comments to ask for clarification. Post a solution as an answer.
34,775 reputation · 05 May 2020, 09:18 UTC
To build on the previous answer, it is important to highlight a critical architectural risk: destructive schema changes. Since pm2 deploy revert only handles the file system, any migration that dropped a column or renamed a table in the failed release will cause the reverted (older) code to crash immediately upon restart, as it expects the old schema to exist.
To mitigate this without a native post-revert hook, consider these verification steps for your rollback pipeline:
undo commands are executed.