~/blog/immutable-images-promotion-blue-green
Build once, promote the digest: trunk-based Git, immutable images and blue/green deploys
The release setup I put across every VarnueAI service: one trunk, PR security gates, sha-tagged images built once, automatic deploys to dev/UAT, a manual dispatch that promotes the exact UAT digest to production, and zero-downtime blue/green swaps behind Nginx.
On this page
At VarnueAI I put every service (product backends and frontends, the Edge admin panel, and our Keycloak) onto one release pattern, so shipping works the same way in every repository. It comes down to five rules:
- One trunk.
mainis the only long-lived branch. - Build once. Every merge produces one immutable image, tagged by commit.
- Promote, don't rebuild. Production runs the exact digest UAT ran.
- Deploy without downtime. Production swaps blue/green behind Nginx, with health checks before and after traffic moves.
- Rollback is a promotion. Going back means promoting an older commit through the same path.
The flow
Trunk-based: short branches, one main
There are no develop, staging or release branches. Work happens on short-lived branches (feat/…, fix/…, chore/…) that merge into main through a pull request, usually within a day or two. Environments are deployment targets, not branches: main feeds dev/UAT automatically, and production is a decision about which commit on main to run.
This removes a whole class of problems. Nothing is merged "up" from staging to production, so production can't receive a change UAT never saw, and nobody resolves the same conflict twice.
The PR gate
ci.yml runs on every pull request to main:
- Gitleaks on the PR's own commits only (
base.sha..head.sha), so an old leak in history doesn't block every PR forever, and a new one always does. npm audit --omit=dev --audit-level=high: production dependencies only.- Tests.
- Docker build + Trivy scan of the image that would ship, failing on fixable HIGH and CRITICAL vulnerabilities. For Keycloak the scan is report-only, because fixes arrive by bumping the upstream version, not by our code.
Gitleaks and Trivy are pinned to exact versions and commits. A floating tag that disappears upstream (it happened) breaks every pipeline at once.
Build once: immutable, sha-tagged images
A push to main builds exactly one image and pushes it to GHCR:
- name: Compute tags
id: meta
run: |
REPO_LOWER=$(echo "${{ github.repository }}" | tr '[:upper:]' '[:lower:]')
SHORT_SHA=$(echo "${{ github.sha }}" | cut -c1-7)
echo "short_sha=${SHORT_SHA}" >> "$GITHUB_OUTPUT"
echo "dev_image=ghcr.io/${REPO_LOWER}:dev-${SHORT_SHA}" >> "$GITHUB_OUTPUT"
- uses: docker/build-push-action@v5
with:
push: true
cache-from: type=gha
cache-to: type=gha,mode=max
tags: ${{ steps.meta.outputs.dev_image }}There is no latest tag. Every image is named after the commit it was built from, and a tag never moves. "What's running in UAT?" is answered by docker ps.
Configuration belongs at runtime
Build once only works if the image contains no environment. Backends already read .env at start. Frontends were the problem: Vite inlines VITE_* variables at build time, so a UAT build has UAT URLs baked into the JavaScript. The fix was to read settings when the container starts. A script in nginx's /docker-entrypoint.d/ writes a small /config.js from the container's environment, index.html loads it before the app, and the app prefers it over import.meta.env:
# deploy/40-runtime-config.sh (trimmed), runs at container start
: "${API_URL:?API_URL must be set}"
: "${KEYCLOAK_URL:?KEYCLOAK_URL must be set}"
printf 'window.__EDGE_CONFIG__ = { "apiUrl": "%s", "keycloakUrl": "%s", "keycloakRealm": "%s", "keycloakClientId": "%s" };\n' \
"$API_URL" "$KEYCLOAK_URL" "${KEYCLOAK_REALM:-varnueai}" "${KEYCLOAK_CLIENT_ID:-edge-web}" \
> /usr/share/nginx/html/config.jsA missing or malformed value stops the container at start instead of shipping a broken page. Now one frontend image serves UAT and production.
(One frontend still bakes its production settings at build time. Its promote workflow has an explicit rebuild switch for that case, and moving it to runtime config is on the list.)
Deploy to dev/UAT automatically
Right after the build, the same workflow copies deploy.sh to the VM over SSH and runs ./deploy.sh dev ghcr.io/…:dev-<sha>. In dev, the container is replaced in place: fast, a few seconds of downtime, fine for UAT.
Two details turned out to matter on a VM that hosts many services:
- Each run gets its own Docker credentials. The deploy user's
~/.docker/config.jsonis shared by every pipeline on the host. When two repositories deployed at the same moment, one'sdocker loginreplaced the other's token mid-pull, and GHCR answered 403. Each run now setsDOCKER_CONFIG=$(mktemp -d)and deletes it on exit. - A concurrency group per service and environment queues deploys instead of running them over each other.
Promote the digest to production
Production is a manual workflow_dispatch with one optional input, commit_sha. Leave it empty and you get the tip of main:
promote-to-prod:
environment: prod # protected environment, reviewers optional
if: github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main'
concurrency: { group: svc-prod, cancel-in-progress: false }
steps:
- run: |
FULL_SHA=$(git rev-parse --verify --quiet "${INPUT_SHA:-$GITHUB_SHA}^{commit}")
git merge-base --is-ancestor "$FULL_SHA" HEAD \
|| { echo "::error::only commits on main can be promoted"; exit 1; }
- run: |
docker buildx imagetools inspect "$DEV_IMAGE" >/dev/null \
|| { echo "::error::$DEV_IMAGE was never built and deployed to DEV"; exit 1; }
docker buildx imagetools create --tag "$PROD_IMAGE" "$DEV_IMAGE"Three guarantees come out of that:
- Only commits on
maincan go live. A commit from a feature branch fails the ancestry check. - Only commits that went through UAT can go live. No
dev-<sha>image, no promotion. - Production runs the tested bytes.
imagetools createwrites a new tag that points at the same manifest in the registry. Nothing is pulled, rebuilt or re-pushed, and the job summary prints the digest so anyone can confirmprod-<sha>anddev-<sha>are identical.
For application services, the deploy.sh that runs is always taken from the tip of main, even when promoting an older image: a fix to the deploy script must also apply when you roll back to a commit from last week. Keycloak is the exception. Its realm configuration belongs to the release, so its promotion checks out the promoted commit's realm and scripts.
Blue/green in production
Each backend has two slots on the VM, blue and green, on fixed localhost ports. Nginx sends traffic to whichever upstream file a symlink points at:
# /etc/nginx/upstreams/edge-backend_blue.conf
upstream edge_backend_upstream { server 127.0.0.1:5008; }
# /etc/nginx/upstreams/edge-backend_green.conf
upstream edge_backend_upstream { server 127.0.0.1:5009; }
# sites-available/edgeapi.varnueai.com.conf includes only the active one
include /etc/nginx/upstreams/edge-backend_active.conf; # symlink -> blue or green
# …
location / { proxy_pass http://edge_backend_upstream; }deploy.sh prod <image> then works in steps, and live traffic is untouched until the last possible moment:
- Pull the promoted image.
- Check the config with the new image before anything is replaced:
docker run --rm --env-file .env <image> node src/scripts/check-config.js. A release that would refuse to start never gets a slot. - Run migrations from the new image. A failed migration aborts the deploy with the old version still serving. Migrations must be backward-compatible (expand, then contract in a later release), because the old slot keeps running against the new schema for a while.
- Find the idle slot by reading the symlink, and start the new container there.
- Pre-traffic health check on the idle slot's port. If it fails, remove the container and exit. Users never saw it.
- Switch: point the symlink at the new slot,
nginx -t,systemctl reload nginx. Reload is graceful: old workers finish their in-flight requests. Ifnginx -tor the reload fails, the symlink goes back. - Post-traffic check. Health-check the new slot again under real traffic. If that fails, the symlink flips back to the old slot, which is still running.
- Rollback window. The old container stays up for 30 seconds before it's removed, then old images of this service are pruned (keeping the last three, never one a container still uses).
Every deploy appends one line to deploy-history.log: time, environment, image, slot. "What was running at 14:05?" has an answer.
What doesn't go blue/green
Stateful services. Keycloak runs one instance against a database that its own version upgrades migrate, so two versions side by side would corrupt each other's assumptions. It gets an in-place restart behind a health gate, a verified backup first, and an automatic return to the previous image. The Keycloak post covers it.
Rollback
There is no separate rollback procedure. Run the promote workflow with the commit_sha of the last good release. Its prod-<sha> image already exists, so it swaps in blue/green like any other deploy, typically in a few minutes. For the first 30 seconds after a bad deploy you don't even need that: the old slot is still running, and the automated checks flip back on their own.
What it changed
- "It worked in UAT" now means something. Production runs the same digest UAT approved, with configuration supplied at start.
- Production releases have no downtime, and a bad release never sees traffic: the config check, migrations and the pre-traffic health check all run before the switch.
- Releases are a button, not a session. A production release is one workflow run with a commit id, and the job summary records which commit and digest went live.
- Every change is scanned before merge for leaked secrets, vulnerable dependencies and vulnerable base images, the same way in every repository.
- One pattern everywhere. A new service copies
ci.yml,cd.ymlanddeploy.sh, changes a few names and ports, and inherits all of the above.
If you're starting from scratch
- Tag images by commit. Never deploy
latest. - Move frontend configuration to container start before anything else. Otherwise "build once" is impossible.
- Make promotion check ancestry and existence: only commits on trunk, and only ones that were built and deployed to UAT.
- Keep the old slot alive after the switch and verify again under real traffic. Most failures show up in the first seconds.
- Keep stateful services out of blue/green, and give them backups and health-gated restarts instead.
Linked from
Keep reading
Monthly notes
Get the next one in your inbox.
One email a month on infrastructure, backend design and applied AI. No noise, unsubscribe any time.
Comments (0)
name + comment · no login