Database migrations in Kubernetes
In-app migrations, initContainers, Kubernetes Job and Helm Hooks.
Introduction
In the era of microservices and Kubernetes, managing database migrations has become more complex than ever. Traditional methods of running migrations during application startup are no longer sufficient.
This article explores various approaches to handling database migrations in a Kubernetes environment, with a focus on Golang-based solutions.
The challenge of migrations in Kubernetes
Kubernetes introduces new challenges for database migrations:
Multiple replicas starting simultaneously.
Need for coordination to avoid concurrent migrations.
Separation of concerns between application and migration logic.
Popular migration tools for Golang
As mentioned in another post, there are a different tools you can use to manage your migrations like:
golang-migrate
Widely used and supports numerous databases.
Simple CLI and API.
Supports various migration sources (local files, S3, Google Storage).
goose
Supports main SQL databases.
Allows migrations written in Go for complex scenarios.
Flexible versioning schemas.
atlas
Powerful database schema management tool
Supports declarative and versioned migrations.
Offers integrity checks and migration linting.
Provides GitHub Actions and Terraform provider.
Running migrations in Kubernetes
Inside your code
A naive implementation would be to run the code of the migration directly inside your main function before you start your server.



