Automate Database Migrations in CI/CD Pipelines
In this article
You automate database migrations in a CI/CD pipeline by running migration scripts as a dedicated pipeline stage that executes before application deployment, using a versioned migration tool (like Flyway or Liquibase) and a safe pattern that includes backups, validation, and rollback planning. The standard approach is to treat database schema changes as code, store them in your repository, and have the pipeline apply them automatically—but the exact steps depend on your database, migration tool, and deployment strategy.
Why Database Migrations Need Automation
Database schema changes are a common source of deployment failures. When you deploy application code without updating the database, the app may crash due to missing columns or tables. Manual migrations are error-prone, especially in teams where multiple developers work on the same schema. Automating migrations ensures that every environment—development, staging, production—gets the same schema changes in the same order, reducing drift and making releases predictable.
Version control for your database is just as important as version control for your code. Migration tools track which scripts have already been applied, so you never run the same change twice. This gives you a reliable history and makes it possible to reproduce a database state from scratch.
How Migration Tools Work
Most migration tools follow a similar pattern. You write migration scripts (usually SQL or a tool-specific format) and place them in a directory. Each script has a unique version number or timestamp. The tool reads a metadata table in the database (e.g., flyway_schema_history or DATABASECHANGELOG) to see which scripts have been applied. When you run the tool, it compares the list of scripts in your repository with the ones already applied and runs only the new ones, in order.
For example, with Flyway, you might have files like V1__create_users.sql, V2__add_email_to_users.sql. On a fresh database, Flyway runs both. On an existing database where V1 is already applied, it runs only V2. Liquibase works similarly but uses changelog files (XML, YAML, or SQL) with unique IDs.
Designing a Migration Pipeline Stage
Here’s a typical pipeline flow for a web application with a relational database:
- Build stage: Compile code, run unit tests, and build artifacts.
- Test stage: Run integration tests against a disposable database (e.g., a containerized PostgreSQL).
- Migration stage: Apply migrations to the target environment (staging or production) using the migration tool.
- Deploy stage: Deploy the application code.
The migration stage should be separate from the deploy stage so you can control the order. For production, you might want to run migrations manually after approval, but the goal is to have a one-click or fully automated process.
Choosing the Right Migration Tool
Your choice of tool depends on your database and team preferences. Flyway and Liquibase are the most common open-source options. Flyway is simpler, SQL-first, and works well with PostgreSQL, MySQL, SQL Server, and others. Liquibase is more flexible, supports multiple formats (SQL, XML, YAML), and has features like contexts and preconditions. If you use a managed cloud database (like AWS RDS), you can also use built-in tools like AWS Database Migration Service, but that’s more for data migration than schema versioning.
Consider these factors:
- Database support: Ensure the tool supports your database engine.
- Team familiarity: SQL is universal; XML/YAML may require learning.
- Rollback capabilities: Liquibase has built-in rollback; Flyway requires separate undo scripts (commercial version) or manual rollback.
- Integration with CI/CD: Both tools have CLI and plugins for Jenkins, GitLab CI, GitHub Actions, and others.
Common Problems and How to Avoid Them
Automating migrations isn’t without pitfalls. Here are the most frequent issues and their solutions:
- Long-running migrations: Large tables can lock and cause downtime. Use online schema change tools (like
pt-online-schema-changefor MySQL) or break migrations into smaller steps. - Ordering issues: If you have multiple migration scripts that depend on each other, the tool handles order by version number. Always use sequential versions and never edit an applied migration.
- Environment drift: If a migration fails in production but succeeds in staging, your environments diverge. Always test migrations in a staging environment that mirrors production.
- Secrets management: Database credentials should be stored in your CI/CD system’s secret store, not in the repository.
Safety: Backups and Rollbacks
Before running migrations in production, always take a full backup of the database. Many teams also use point-in-time recovery (PITR) if the database supports it. For rollbacks, you have two options: forward rollback (apply a new migration to undo the change) or restore from backup. Forward rollback is safer for schema changes because it preserves data, but it requires you to write undo scripts. Restoring from backup is simple but may lose recent data changes.
Also, consider using a blue-green deployment pattern where you have two database schemas (old and new) and switch traffic after successful migration. This is complex but eliminates downtime for schema changes that are backward-compatible.
Comparing Migration Strategies
There are two main strategies: expand and contract and parallel change. Expand and contract involves adding new columns or tables first, then deploying code that uses them, then removing old columns in a later migration. This allows zero-downtime deployments. Parallel change (also called expand-migrate-contract) is a specific implementation where you keep both old and new versions of the schema during a transition period.
For example, if you need to rename a column from username to login, you would first add login, then deploy code that reads from login, then remove username in a later migration. This avoids breaking existing code during deployment.
Cost and Maintenance Considerations
Automating migrations has a small upfront cost: you need to set up the tool, write scripts, and integrate with your CI/CD. The ongoing cost is maintaining the scripts and ensuring they run smoothly. However, the cost of manual migrations is often higher due to downtime, errors, and developer time. Most migration tools are open-source and free, but commercial versions offer additional features like rollback and reporting.
Frequently Asked Questions
Can I run migrations automatically in production without human approval?
Yes, but it’s risky. Many teams start with automatic migrations in staging and require a manual approval for production. If you do automate production, ensure you have strong backups, monitoring, and a quick rollback plan. Start with low-risk changes and gradually increase confidence.
What if a migration fails halfway through?
Most migration tools run each script in a transaction if the database supports DDL transactions (e.g., PostgreSQL). If a script fails, the transaction rolls back, and the tool marks it as failed. You can fix the script and re-run. For databases that don’t support transactional DDL (like MySQL), you may need to manually revert the changes or restore from backup.
How do I handle migrations for multiple databases (e.g., separate databases per tenant)?
You can run the migration tool multiple times with different connection strings, either in parallel or sequentially. Some tools support multiple environments or profiles. Ensure your pipeline loops through the list of databases and applies migrations to each.
Should I use a separate migration service or run it in the same pipeline?
Running it in the same pipeline is simpler and keeps everything in one place. A separate service (like a dedicated migration job) can be useful if you have many services sharing a database, but it adds complexity. For most teams, a pipeline stage is sufficient.
Can I test migrations against a production-like database?
Yes, you can use a staging database that is a copy of production (anonymized if needed). Tools like pg_dump or database cloning features in cloud providers can create such copies. This helps catch issues before production.