How to apply database migrations immediately after deploying the database in Kubernetes?
sobes.tech AI
Answer from AI
To apply database migrations immediately after deployment in Kubernetes, init containers or special Jobs are usually used.
Init containers run before the main application container and can perform migrations, such as executing migration scripts or tools like Flyway, Liquibase, Alembic, etc. After the init container completes successfully, the main container starts.
Example of using an init container in a Pod/Deployment manifest:
initContainers:
- name: migrate-db
image: my-migration-tool:latest
command: ["./migrate.sh"]
env:
- name: DB_HOST
value: "mydb-service"
- name: DB_USER
valueFrom:
secretKeyRef:
name: db-credentials
key: username
# other parameters
Job is a separate Kubernetes resource that runs migrations as a separate task. Once the Job completes successfully, it is considered finished. This is convenient if migrations need to be run manually or on a schedule.
Migrations can also be embedded into the application's startup script, but this is less flexible and can complicate the startup logic.
Thus, the most common and reliable way is to use init containers for automatic migration application before starting the application.