Flyway Setup for Database Migration Automation
In this article
- What Flyway Does and Why It Matters
- Prerequisites and Initial Setup
- Choosing an Integration Approach
- Writing Migration Scripts
- Running Migrations in CI/CD and Production
- Common Pitfalls and How to Avoid Them
- Comparing Flyway with Alternatives
- Costs and Licensing
- Safety and Best Practices
- Frequently Asked Questions
To set up Flyway for database migration automation, you install the Flyway command-line tool or add its library to your application, configure a database connection, and place your SQL migration scripts in a designated folder (default: flyway/sql). Then run flyway migrate (or trigger it via your build tool) to apply pending migrations in version order. This article explains the full setup process, how Flyway tracks applied migrations, how to choose between the command-line, Maven/Gradle, and API approaches, and common pitfalls to avoid.
What Flyway Does and Why It Matters
Flyway is an open-source database migration tool that versions your schema changes. Instead of manually running SQL scripts or relying on ad-hoc updates, Flyway keeps a history table (default: flyway_schema_history) in your database. Each migration file has a version number, a description, and a checksum. When you run flyway migrate, Flyway compares the applied versions in the history table with the files in your migration folder and applies any missing ones in order.
This gives you repeatable, automated schema evolution across environments—development, staging, production—without guessing which scripts have already run. It also detects if someone modifies an already-applied migration (checksum mismatch) and fails fast, preventing silent drift.
Prerequisites and Initial Setup
Before you begin, ensure you have:
- A supported database (PostgreSQL, MySQL, MariaDB, Oracle, SQL Server, SQLite, and others). Flyway community edition supports many, but some advanced features require Teams edition.
- Java 8+ if using the command-line tool (it runs on JVM) or if integrating via Maven/Gradle.
- Access to the database credentials with sufficient privileges to create tables and execute DDL.
Download the Flyway command-line tool from the official website (or use your package manager). Extract it, and you have a flyway executable. For a quick start, create a directory structure like this:
my-project/
flyway/
conf/
flyway.conf
sql/
V1__create_users.sql
V2__add_email_to_users.sql
In flyway.conf, set your connection details:
flyway.url=jdbc:postgresql://localhost:5432/mydb flyway.user=dbuser flyway.password=secret
Then run flyway migrate from the project root. Flyway will create the history table and apply the two scripts.
Choosing an Integration Approach
Flyway offers several ways to run migrations, depending on your stack:
- Command-line tool: Best for standalone scripts, CI/CD pipelines, and teams not using Java. Simple to invoke in a Docker container or a shell step.
- Maven/Gradle plugin: Ideal for Java projects. Add the plugin to your
pom.xmlorbuild.gradle, and migrations run as part of the build lifecycle (e.g.,mvn flyway:migrate). - Flyway API (Java): For programmatic control within an application, e.g., running migrations on startup. Useful for embedded databases or microservices.
- Docker image:
flyway/flywayimage lets you run migrations in a container, perfect for Kubernetes jobs or docker-compose setups.
For a typical Spring Boot application, the Flyway dependency auto-configures and runs migrations on startup if you place scripts in src/main/resources/db/migration. That’s the simplest Java integration.
Writing Migration Scripts
Flyway uses a naming convention for migration files:
- Versioned migrations:
V1__description.sql,V2__description.sql– applied once, in order, and never modified after application. - Repeatable migrations:
R__description.sql– re-applied whenever the checksum changes, useful for views or stored procedures. - Undo migrations:
U1__description.sql– available in Teams edition, for rolling back a specific version. Not supported in the open-source version.
Version numbers can be numeric (1, 2, 3) or dotted (1.1, 1.2). The description is arbitrary but should be meaningful. For example:
V1__create_users_table.sql:
CREATE TABLE users (
id BIGSERIAL PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE
);
V2__add_name_column.sql:
ALTER TABLE users ADD COLUMN name VARCHAR(100);
Each script runs in a transaction by default (on databases that support DDL transactions). If a script fails, Flyway rolls back that script’s transaction, but previously applied migrations remain.
Running Migrations in CI/CD and Production
In automated environments, you typically run flyway migrate as a step in your pipeline. For example, in a GitHub Actions workflow, you might have a job that uses the Flyway Docker image:
docker run --rm -v $PWD/sql:/flyway/sql \ -e FLYWAY_URL=jdbc:postgresql://db:5432/app \ -e FLYWAY_USER=user -e FLYWAY_PASSWORD=pass \ flyway/flyway migrate
For production, consider these practices:
- Run migrations as a separate step before deploying new application code, not during startup, to avoid multiple instances racing.
- Use
flyway validatein CI to catch checksum mismatches early. - Back up the database before running migrations in production, even though Flyway is designed to be safe.
- For large tables, write migrations that minimize locking (e.g., add columns with defaults in PostgreSQL 11+).
Common Pitfalls and How to Avoid Them
Here are frequent issues users encounter:
- Checksum mismatch: Editing an applied migration changes its checksum. Flyway fails on next run. Solution: never edit applied versioned migrations; create a new version instead.
- Out-of-order migrations: If you add a migration with a lower version than an already applied one, Flyway errors by default. Use
outOfOrder=trueif you must, but it’s better to keep versions sequential. - Connection issues: Ensure the JDBC URL is correct and the database is reachable. Test with
flyway infoto see status. - Permissions: The database user needs rights to create the history table and execute DDL. In restricted environments, pre-create the history table with appropriate grants.
- SQL syntax errors: Flyway executes scripts as-is; a syntax error aborts the migration. Test locally with a scratch database.
Comparing Flyway with Alternatives
Flyway is not the only migration tool. Common alternatives include:
- Liquibase: Similar but uses XML/YAML/JSON changelogs (or SQL) and supports more advanced features like contexts and preconditions. Steeper learning curve.
- Alembic (Python/SQLAlchemy): For Python projects, tightly integrated with SQLAlchemy, but requires Python environment.
- Prisma Migrate: For Node.js/TypeScript with Prisma ORM, good for schema-first workflows, but less flexible for raw SQL.
- Custom scripts: Writing your own versioning is error-prone; Flyway gives you a battle-tested history mechanism.
Choose Flyway if you want a lightweight, SQL-centric tool that works across many databases and integrates easily with Java or CI/CD. Liquibase might be better if you need database-agnostic changelogs (e.g., generating migrations for multiple DB types from one definition).
Costs and Licensing
Flyway Community Edition is open-source (Apache 2.0) and free for all uses. It covers core features: versioned migrations, repeatable migrations, and the command-line/API. Flyway Teams Edition adds features like undo migrations, dry runs, and advanced callbacks, and requires a paid license. For most teams, the community edition is sufficient. There is no cost for the tool itself, but you should consider the operational cost of maintaining migrations and testing them in staging environments.
Safety and Best Practices
Database migrations are risky because they change schema in production. Follow these safety rules:
- Always back up the database before running migrations in production.
- Test migrations on a copy of production data in a staging environment.
- Use version control for migration scripts; they are code.
- Make migrations idempotent where possible (e.g., use
IF NOT EXISTSwhere supported) to avoid failures on partial runs. - Monitor migration logs and set up alerts for failures.
- For large data changes, break them into smaller steps or use batch processing within a migration script.
Flyway itself is safe: it uses locks to prevent concurrent migrations, and the history table ensures each script runs exactly once. However, a poorly written script can still cause downtime.
Frequently Asked Questions
How do I set up Flyway with Spring Boot?
Add the Flyway dependency to your pom.xml or build.gradle. Place your SQL scripts in src/main/resources/db/migration. Spring Boot auto-configures Flyway and runs migrations on startup using the datasource defined in application.properties. If you need to disable it, set spring.flyway.enabled=false.
Can I use Flyway with an existing database that has no history table?
Yes. Flyway can baseline an existing database. Run flyway baseline after configuring the connection. This creates the history table and marks all existing migrations (up to the baseline version) as applied. For example, if you have existing tables and want to start versioning from now, set baselineVersion=1 and your first new migration will be V2__....
What happens if two team members create migrations with the same version?
Flyway will detect a conflict when the second person runs flyway migrate because the history table already has a record for that version. The migration fails with an error. To avoid this, coordinate version numbers (e.g., use a shared branch or assign ranges per developer) or use a CI check that runs flyway info to detect duplicates.
How do I roll back a migration?
In the community edition, there is no built-in undo. You must write a new migration that reverses the changes (e.g., V3__drop_column.sql). In Teams edition, you can use undo migrations (U1__...) to revert a specific version. Always test rollback scripts in staging.
Can I run Flyway migrations in parallel across multiple instances?
Flyway uses a lock on the history table to prevent concurrent migrations. When multiple instances start simultaneously, one will acquire the lock and run, others will wait. However, it’s safer to run migrations as a separate step before deploying new code, especially if your application startup has long-running migrations.
Does Flyway support multiple databases in one project?
Yes, you can configure multiple Flyway instances with different flyway.url settings, either by using separate configuration files or by running the command-line tool multiple times with different -configFiles arguments. In Spring Boot, you can define multiple datasources and configure Flyway for each.