Skip to content

Blue Green Deployment

A.s. edited this page Dec 1, 2026 · 14 revisions

Blue/green deployment (zero downtime)

Optional, per host. An alternative to the stop-everything flow of Updating for the backend, which stays valid and is the default on every host that has not run make bg-init. Use this page only on hosts where the team agreed to it (so far parkour-dev and parkour-test). The new release starts next to the old one, is migrated and checked, and only then gets traffic. The old one finishes its running requests and is stopped. Nobody is logged out, and nobody keeps talking to the old backend afterwards.

  1. How it works
  2. One-time setup
  3. Every release
  4. Migrations: the one rule
  5. Rollback
  6. Going back to the old process
  7. Cron and housekeeping
  8. Docker and Podman
  9. What this does not cover

How it works

browser -> parkour2-nginx -- misc/active/backend.conf --> parkour2-django-blue   (or -green)
                                                     \--> parkour2-postgres (shared by both)
  • Two backend containers, parkour2-django-blue and parkour2-django-green, defined in misc/bluegreen.yml. One serves; the other is stopped (it is the rollback target).
  • nginx reads its upstream from misc/active/backend.conf. A flip rewrites that file and runs nginx -s reload. A bad config fails nginx -t and nothing changes. The reload is graceful: old workers finish their in-flight requests (up to worker_shutdown_timeout 180s) before exiting. The flip waits for the new color to appear, then needs 20 successful requests through nginx, then drains the old workers.
  • Sessions survive because they live in Postgres (django_session) and both colors read the same SECRET_KEY from misc/parkour.env.ignore. That is the real, untracked env file; the tracked misc/parkour.env is only a template that make clean restores, so the blue/green containers never read it. bg-deploy refuses to start without parkour.env.ignore, and compares SECRET_KEY, DATABASE_URL and READONLY_DATABASE_URL of the new container with the live one before migrating.
  • No old backend afterwards: once nginx's old workers are done, the old container is stopped. A client cannot reach it (it would get a 502, not old code).
  • Unlike docker-compose.yml, the code is inside the image (no ./backend bind mount). Two releases can run at once, and a git checkout on the host cannot change a running backend.
  • curl -skI https://127.0.0.1/login/ | grep -i x-pk2-color shows which color nginx serves.

One-time setup

Do it first on parkour-dev. It recreates nginx, so expect a few seconds of downtime. Pick a quiet moment and give the usual heads-up.

  1. Deploy the release that contains this feature the old way (the Updating steps), so ~/parkour2 has misc/bg-deploy.sh.
  2. make --directory ~/parkour2 bg-init
    • Creates misc/active/backend.conf pointing at the existing parkour2-django (color legacy), and recreates nginx so it mounts misc/active/.
  3. make --directory ~/parkour2 bg-status should print live: parkour2-django and HTTP/... 200.
  4. First blue/green release: make --directory ~/parkour2 bg-deploy. The legacy container is stopped and removed at the end (its bind-mounted code is the new checkout, so it is no rollback target). The next releases alternate blue and green.

Warning

After the setup, make prod refuses to run on that host (it would leave nginx on the old backend), and make down and docker system prune -a must not be used. Postgres, vite and nginx stay in the parkour2 compose project; only the backend moves to parkour2-bg. Targets that hard-code parkour2-django (shell, reload-code, migrations, lint-migras...) do not apply there: use make manage CMD="..." or docker exec parkour2-django-<color> ....

Every release

Preparation (heads-up, certificate, Actions, changelog, git tag yy.mm.dd && git push --tags) is the same as in Updating. Then, on the VM:

cd ~/parkour2
git fetch --tags
git checkout yy.mm.dd          # or: git switch --detach yy.mm.dd
make bg-deploy ARGS=yy.mm.dd

bg-deploy refuses to start if HEAD is not that tag, or if backend/, shared/ or backend.Dockerfile have uncommitted changes (the image is built from this checkout). It then does, in this order:

  1. save-postgres and rsnapshot halfy: backup before anything changes.
  2. Builds the image parkour2-django:<version> and starts the idle color. The live one keeps serving.
  3. Runs migrate --plan on the new container and checks it against the rules below. Asks for a y (skip with --yes).
  4. migrate and collectstatic from the new container, then GET /login/ directly on it.
  5. Flip: rewrites backend.conf, nginx -t, reload, then 20 requests through nginx must all be 200 with the new X-Pk2-Color. Otherwise it restores the old config by itself.
  6. Waits for nginx's old workers (up to 190 s), then docker stop -t 180 on the old color: gunicorn finishes running requests first.
  7. save-postgres tar-old-migras, rsnapshot halfy, and an entry in ~/last.txt.

Note

A release that fails its healthcheck (broken code, stale max_migration.txt...) never gets the flip: the deploy stops at step 3 and the live color keeps serving. Checked on pk2test with a deliberately broken release.

Note

tar-old-migras is not the old "before git checkout" backup any more: it packs the migrations of the new release. The pre-deploy safety net is the dump from step 1 (misc/latest.sqldump points at the latest one, but step 7 makes a new one: keep the one named in step 1's output if you may need to restore).

Migrations: the one rule

Between the migration and the flip, the old code runs on the new schema. So a release's migrations must be additive (new tables, new nullable or defaulted columns, new indexes). Removing or renaming goes into the next release (add, switch the code over, remove later).

bg-deploy reads each pending migration file and stops when it finds RemoveField, DeleteModel, RenameField, RenameModel, AlterField, AlterModelTable, AlterUniqueTogether, AlterIndexTogether, RemoveIndex or RemoveConstraint. RunPython and RunSQL only print a warning for you to read. Then choose:

Flag Meaning Downtime
--compatible You checked that the old code still works with the new schema (e.g. an AlterField that only widens). Deploy as usual. none
--breaking Maintenance window, see below. for however long migrate runs, plus seconds

The check is a text search, not a proof. A RunPython that deletes or rewrites rows passes the gate: read what it prints.

Without a flag the deploy stops at the gate: nothing is applied, the live color keeps serving, and the new color is left running with no traffic (the next deploy replaces it).

How --breaking works

Use it when old code cannot run on the new schema at all (dropped column it still reads, renamed table). The deploy takes a maintenance window in exchange for never mixing old code with the new schema:

  1. The live color is stopped first. From that moment nginx has no backend: every request gets a 502.
  2. migrate runs on the new color, for however long the migration takes.
  3. Flip: nginx reloads, serves the new color, the 502s end. The stopped old color is retired; there is nothing left to drain.

Measured on pk2test with two trivial migrations: the whole 502 window was under a second. A real data migration stretches it by however long it runs, so announce the window accordingly.

If the deploy fails midway (failed healthcheck, failed traffic check), users stay on 502: the old color is stopped and the new one is not live. Run make bg-rollback to start the old color and give it traffic again. Mind that the database may already be migrated: for a truly breaking migration, restore the dump from step 1 of the release first (see Backup & Restore).

Rollback

make bg-rollback

Starts the stopped previous color, checks it, flips to it, drains and stops the faulty one. Database migrations are not reverted, which is fine for additive ones. After a --breaking migration, restore the dump taken in step 1 instead (see Backup & Restore).

Only one version back is kept. Both colors keep their image until the next deploy replaces one of them.

Going back to the old process

Blue/green is a per-host choice. To return a host to the Updating flow:

cd ~/parkour2
make save-postgres                                                      # make prod deletes the database volume: dump first
docker compose -f misc/bluegreen.yml --project-name=parkour2-bg down   # stops and removes blue and green
rm misc/active/backend.conf
make prod
docker cp "$(readlink -f misc/latest.sqldump)" parkour2-postgres:/tmp/restore.dump
docker exec parkour2-postgres pg_restore --clean --if-exists --no-owner --single-transaction --exit-on-error \
	-U postgres -d postgres /tmp/restore.dump
docker exec parkour2-postgres rm -f /tmp/restore.dump

make prod is stop-everything: it deletes the parkour2_pgdb volume, recreates parkour2-django, nginx and rsnapshot, and deploy-nginx writes misc/active/backend.conf again, pointing at parkour2-django. The dump and restore above bring the data back. Expect the usual downtime. Tested on pk2test: the legacy stack came back, nginx served parkour2-django (x-pk2-color: legacy), and the restored database matched the dump (same row counts).

Nightly refresh of a staging host

misc/bg-nightly.sh replaces the old nightly make clean import-pgdb dev-migras on a host that runs blue/green (parkour-test). Never on parkour: it overwrites the database.

  1. Updates the checkout (git checkout -B $BRANCH origin/$BRANCH, optionally merges $MERGE_REF; a conflict stops the run and nothing is deployed).
  2. make import-pgdb: dumps production over SSH and copies the dump. The run stops if the dump is older than 60 minutes.
  3. Restores it in one transaction (pg_restore --clean --single-transaction --exit-on-error, excluding django_session so the host keeps its own logins): a broken dump leaves the current data untouched. The dump carries production's schema and django_migrations, so the next step applies exactly the migrations of the new code.
  4. misc/bg-deploy.sh deploy --yes --compatible: the usual swap. Nobody confirms at 05:00, so the migration gate is skipped (--compatible): a schema-breaking migration can briefly break the live color on staging. Use BG_FLAGS=--breaking to take a maintenance window instead.

Between steps 3 and 4 the live color runs against production's schema, which can be older than its own code, so it may show errors for the minutes the deploy takes. Any failure after step 3 leaves that color running; read ~/bg-nightly.log.

0 5 * * * BRANCH=develop /root/parkour2/misc/bg-nightly.sh

To test an unmerged branch on a staging host, use BRANCH=<branch> MERGE_REF=origin/develop.

Cron and housekeeping

Two lines in the current crontab break this scheme or never worked:

  • Image pruning. docker system prune -a -f --volumes deletes the stopped color's container and image, which kills the rollback. On blue/green hosts use the -a image-only form, which keeps the image of an existing stopped container and never touches stopped containers or volumes:

    0 */6 * * * docker image prune -a -f
    

    This is already applied on parkour, parkour-dev and parkour-test (changed in place, same schedule).

    Also remove the docker system prune -a -f at the end of the old Updating flow, and the nightly docker-compose ... build (it builds the legacy service, not the blue/green images; removed from parkour-test's crontab).

  • Django commands. docker-compose exec -it parkour2-django ... fails under cron (no TTY, and cron's working directory is /root, not the repo), and it names a container that no longer exists after the setup. On parkour the rows of clearsessions have been piling up since 2023: 2996 rows, 66 still valid, when checked. Use:

    0 5 * * 6 make -C /root/parkour2 manage CMD="clearsessions"
    0 4 * * 6 make -C /root/parkour2 manage CMD="clean_old_history --days 800 --auto"
    0 * * * * make -C /root/parkour2 manage CMD="clean_duplicate_history --minutes 90 --auto"
    

    make manage runs docker exec on whichever color is live.

THROW-AWAY WARNING, first blue/green deploy on parkour only (delete this box after it). The prod crontab still has 0 0 * * 6 docker-compose exec -it parkour2-django python manage.py clearsessions. It never worked (no TTY under cron), and after the first flip the container parkour2-django is removed, so the line will keep failing. The prune line above is already fixed, but this one is left on purpose until the PR is merged and parkour has the make manage target. After the first successful make bg-deploy on parkour, replace that line with 0 5 * * 6 make -C /root/parkour2 manage CMD="clearsessions". Ask before you run clearsessions by hand: the table holds about 3000 rows, 66 still valid.

Docker and Podman

The scripts use only the plain docker CLI and compose v2 flags, so they run on both:

  • Docker with compose v2 (>= 2.20), as on parkour and parkour-dev.
  • Podman 5 with podman-compose 1.5, where docker is a wrapper and docker compose calls podman-compose.

Checked on podman 5.8.2 with a throwaway project that runs the real misc/bluegreen.yml (only the resource names changed) plus the real nginx configs: both colors came up healthy, restart: unless-stopped, extra_hosts: host-gateway, external network/volumes all behave, a missing PK2_VERSION errors out (exit 1), and flipping misc/active/backend.conf + nginx -s reload switches X-Pk2-Color from blue to green. The full misc/bg-deploy.sh (a copy with only container/network/volume names and the probe port changed) also ran end to end: legacy-to-blue deploy, blue-to-green deploy, rollback, migration-gate refusal (rc=1, nothing applied, live color unchanged), and --compatible override. The docker inspect formats and docker exec -i ... python - in bg-deploy.sh work too. One cosmetic difference: docker stop -t 180 on a podman container that ignores SIGTERM waits the full 180 s before SIGKILL; gunicorn traps SIGTERM, so on a real backend it exits immediately.

Differences to know:

  • make bg-status shows the image as localhost/parkour2-django:<version> under podman. Cosmetic.
  • unless-stopped only restarts the live color after a host reboot if podman-restart.service is enabled.
  • Errors from docker compose come from podman-compose (Python tracebacks), not from compose v2.

What this does not cover

  • Frontend (parkour2-vite). npm run build still replaces dist/ in place. A tab opened before the release may ask for a hashed file that is gone until the user reloads.
  • Static files are not content-hashed and share one volume: collectstatic overwrites them while the old color still serves. Only matters if a release changes admin assets.
  • Debounced materialized view refresh is a 2 s in-process timer. The drain wait covers it.
  • Logs of both colors go to one volume, parkour2_bg_logs. They write the same rotating files for the minutes both are alive.

Clone this wiki locally