How to Run Database Migrations on Deploy With GitLab CI/CD
A migrate stage that runs before deploy, guarded by a resource_group, applies schema changes exactly once per release.
Put migrations in their own stage that the deploy needs:, and set a resource_group so concurrent pipelines serialize and never run migrations simultaneously.
Steps
- Add a
migratestage beforedeploy. - Run your migration command there.
- Set a
resource_groupso migrations serialize. - Make
deploydeclareneeds: [migrate].
.gitlab-ci.yml
.gitlab-ci.yml
stages: [migrate, deploy]
migrate:
stage: migrate
resource_group: production_db
script:
- ./manage.py migrate --noinput
rules:
- if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'
deploy:
stage: deploy
needs: [migrate]
script: ./deploy.sh
environment:
name: productionGotchas
- Write backward-compatible migrations so old pods keep working during the rollout.
- Without a
resource_group, two pipelines can race and corrupt the schema.
Related guides
How to Roll Back a Deployment With GitLab CI/CDRoll back a deployment in GitLab CI/CD with a manual rollback job that redeploys a previous image tag passed…
How to Deploy to Kubernetes With kubectl in GitLab CI/CDDeploy to Kubernetes from GitLab CI/CD using kubectl set image and kubectl rollout status, updating a Deploym…