Skip to content
Latchkey

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 migrate stage before deploy.
  • Run your migration command there.
  • Set a resource_group so migrations serialize.
  • Make deploy declare needs: [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: production

Gotchas

  • 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

Run this faster and cheaper on Latchkey managed runners. Start free →