Chapter 12 · Lesson 10 of 10
CI/CD and automation

Rollback and release strategy in a CI/CD pipeline

A pipeline rollback redeploys a previous, known-good immutable image tag, triggered by a health check failure or by hand, and works only if database changes are backward compatible.

By the end you will

Add a health gate, an automatic rollback step and a manual rollback workflow that redeploys a previous image tag.

Time
25 min
Level
Intermediate
Check
4 questions
You need
  • A deploy workflow that runs a script on your server
  • Images tagged with the commit SHA or version

A health gate decides whether a release stays

After a deploy the pipeline checks health, keeps the release when it passes and redeploys the previous tag when it fails.
  1. The pipeline deploys the new tag, then the health gate polls the health endpoint several times.
  2. When every check passes, the job succeeds and v2 stays live.
  3. When the checks fail, the pipeline redeploys the previous tag and marks the run as failed.
Static diagram
  1. Deploy v2releaseHealth gate
  2. Health gatepassesv2 stays live
  3. Health gatefailsBack to v1

A deploy that you cannot undo is a gamble. A pipeline makes rollback cheap by keeping every released image, deploying by an immutable tag, and checking health right after each deploy. This lesson adds a health gate, an automatic rollback and a manual rollback workflow to the SSH deploy from Deploy over SSH from GitHub Actions. The ideas behind it are in Rollbacks and Zero-downtime deploys.

How it works#

Every release is an image with a tag that never changes, for example sha-1a2b3c4 or 1.2.0. The server runs one tag at a time. A deploy swaps the tag. A health gate then asks the app whether it is serving. If yes, the release is done. If no, the pipeline redeploys the previous tag. Because the old image still exists in the registry, going back is a pull and a restart, with no rebuild. A rollback is only safe if the database still works with the old code, which is why migrations need care.

Step 1: Keep tags immutable#

Never reuse a tag. latest and a moving stable tag cannot answer “what exactly ran yesterday?”. Tag by commit SHA or by version, and keep old ones in the registry long enough to roll back to. Do not clean up the tag a server currently runs or the one before it. Also record which tag is live. A tiny file on the server works:

bash
echo "$TAG" > /srv/app/.current-tag

The deploy script reads the old value into a variable before overwriting it, which is what the automatic rollback uses.

Step 2: Add a health endpoint and gate#

Your app needs an endpoint that returns success only when it can serve, for example /healthz. See Docker health checks. After the deploy step, loop on it with a deadline:

bash
for i in $(seq 1 30); do
  if curl -fsS --max-time 5 https://example.com/healthz > /dev/null; then
    echo "healthy"
    exit 0
  fi
  echo "waiting ($i)"
  sleep 5
done
echo "unhealthy after retries" >&2
exit 1

curl -f makes HTTP errors return a non-zero exit code. --max-time stops one slow request from hanging the loop. The loop is bounded, so the job fails in a known time instead of hanging. A health check that always returns 200 proves nothing, so make it touch what the app needs, such as the database connection.

Step 3: Roll back automatically on failure#

Put the gate in the deploy job, then add a step that runs only on failure:

yaml
name: deploy

on:
  workflow_dispatch:
    inputs:
      tag:
        description: "Image tag to deploy, for example sha-1a2b3c4"
        required: true
      previous_tag:
        description: "Known-good tag to fall back to"
        required: true

permissions:
  contents: read

concurrency:
  group: deploy-production
  cancel-in-progress: false

jobs:
  deploy:
    runs-on: ubuntu-latest
    environment: production
    steps:
      - name: Prepare SSH
        run: |
          install -m 700 -d ~/.ssh
          printf '%s\n' "$DEPLOY_SSH_KEY" > ~/.ssh/id_ci
          chmod 600 ~/.ssh/id_ci
          printf '%s\n' "$DEPLOY_KNOWN_HOSTS" > ~/.ssh/known_hosts
        env:
          DEPLOY_SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }}
          DEPLOY_KNOWN_HOSTS: ${{ secrets.DEPLOY_KNOWN_HOSTS }}

      - name: Deploy new tag
        env:
          TAG: ${{ inputs.tag }}
        run: ssh -i ~/.ssh/id_ci deploy@203.0.113.10 "$TAG"

      - name: Health gate
        run: |
          for i in $(seq 1 30); do
            curl -fsS --max-time 5 https://example.com/healthz > /dev/null && exit 0
            sleep 5
          done
          exit 1

      - name: Roll back on failure
        if: failure()
        env:
          PREVIOUS_TAG: ${{ inputs.previous_tag }}
        run: ssh -i ~/.ssh/id_ci deploy@203.0.113.10 "$PREVIOUS_TAG"

if: failure() runs the step only when an earlier step failed. It reuses the same restricted SSH key and the same script, so rollback is just another deploy of the old tag. The inputs go through env instead of ${{ }} inside the shell line, because an expression is pasted into the script before it runs on the runner, so a crafted value could run commands there even though the server validates the tag. Pass the previous tag automatically if your release step records it.

Step 4: Provide a manual rollback#

The same workflow doubles as a manual rollback: run it from the Actions tab with the old tag as tag. For a cleaner interface, create a second workflow that takes only tag and runs the deploy and the health gate. Manual rollback matters because a release can pass the health check and still be wrong, for example a bug found an hour later. You decide, you pick the tag, and you press the button.

Step 5: Make migrations backward compatible#

Code rollback takes seconds. A schema change may not roll back at all. Use two releases for any breaking schema change, often called expand and contract:

  1. Expand. Add the new column or table, nullable or with a default. Old code ignores it, new code uses it.
  2. Migrate. Backfill data while both versions work.
  3. Contract. In a later release, after the old code is gone, remove the old column.

Never drop or rename a column in the same release that stops using it. Take a database backup before a risky migration, and test the restore (see Test a backup by restoring it). For the full container walk-through, read the blog guide Roll back a failed Docker deploy and Zero-downtime Docker deploys with rollback.

Check it worked#

Test rollback before you need it. Deploy a deliberately broken version to a staging environment, for example one whose /healthz returns 500, and watch the gate fail and the previous tag come back. Confirm the server runs the old image (docker compose ps shows the old tag) and that the site answers. Then run the manual rollback with a known tag and confirm the same. A rollback you have never run is an assumption.

Edge cases and gotchas#

  • The old image was pruned. Registry cleanup or docker image prune on the server can remove the tag you want. Keep at least the last few releases.
  • Health check too shallow. A static ok endpoint passes while the database is unreachable. Check dependencies.
  • Health check too strict. A slow start fails a 30-second window. Tune the retries to your app’s real start time, not a guess.
  • Rollback hides the cause. After rolling back, read the failed release’s logs before trying again. See Read container logs.
  • Cancelling a deploy halfway. Keep cancel-in-progress: false for deploy groups so a new run waits.
  • Config changes. Rolling back the image does not roll back changed environment variables or compose files. Version those with the code.
  • Passing health but serving errors. Some failures show up only under real traffic. See Fix a deploy that passes health checks but serves errors.

Troubleshooting#

SymptomLikely causeFix
manifest unknown on rollback pullOld tag deleted from the registryKeep recent tags, or pick another known-good tag
Health gate fails but app works by handWrong URL, proxy not ready or DNSTest the exact URL from the runner’s point of view
Rollback step never runsMissing if: failure()Add it to the step
Job hangs on the gateNo --max-time on curlAdd a timeout and a bounded loop
App crashes after rollbackMigration not backward compatibleRestore from backup, use expand and contract next time
Two deploys collideNo concurrency groupAdd one with cancel-in-progress: false
refusing tag: from the scriptInput does not match the allowed patternPass a tag like sha-1a2b3c4

Quick reference#

bash
# health gate
curl -fsS --max-time 5 https://example.com/healthz

# manual rollback: run the deploy workflow with the old tag
# server check
docker compose ps
cat /srv/app/.current-tag
yaml
- name: Roll back on failure
  if: failure()
  env:
    PREVIOUS_TAG: ${{ inputs.previous_tag }}
  run: ssh -i ~/.ssh/id_ci deploy@203.0.113.10 "$PREVIOUS_TAG"

Next#

Continue with What to monitor first.

Check what you learned4 questions
1What makes a rollback quick and reliable?
2What should a post-deploy health check do when the app never becomes healthy?
3Which migration is safest for rollback?
4Why use a concurrency group on the deploy and rollback workflows?

Frequently asked questions

How do I roll back a deployment in a CI/CD pipeline?

Redeploy the previous known-good image tag. A manual workflow_dispatch workflow that takes the tag as an input is the simplest way, and it uses the same deploy script as a normal release.

Why should image tags be immutable?

If a tag can be overwritten, the same name can mean different code on different days, so you cannot reliably return to a previous state. Tag with the commit SHA or a version and never reuse the tag.

What is a health gate?

A step after the deploy that requests a health endpoint until it succeeds or a deadline passes. If it never succeeds, the job fails and can trigger a rollback.

Why do database migrations make rollbacks hard?

Code can go back to the previous version in seconds, but a migration that dropped or renamed data cannot. Make migrations backward compatible so the old code still works against the new schema.

Sources

View MD Edit
Share
Helpful?
Progress is saved in this browser only.

Keep going: guides and tutorials

View MD Edit
Share
Helpful?
Run this on your own server

Levelrail deploys apps from git with health-checked releases and one-click rollback.

docker pull ghcr.io/glincker/levelrail:latest Install Levelrail From GLINR Studios