# Deploy: static sites, servers over SSH, Kubernetes, and rollbacks

Ship the artifact you built: a static site to GitHub Pages, a release to a server over SSH with an atomic switch and automatic rollback, and an image to Kubernetes with a safe rolling update.

Course: [CI/CD Pipelines](https://devops.rajeev.pro/courses/cicd), lesson 7. About 45 minutes, intermediate. Source: https://devops.rajeev.pro/courses/cicd/07-deploy

## What you will learn

- Deploy a static site from CI to GitHub Pages
- Deploy a release to a server over SSH, switching atomically with a symlink
- Health-check after every deploy, and roll back automatically when it fails
- Pin the server's host key in CI instead of trusting whatever answers
- Roll out a new image on Kubernetes without downtime, and undo it
- Choose a rollback for each kind of deploy before you need one
- Choose between rolling, blue/green, canary and feature flags, and know what each costs and how each rolls back

## Three targets, one rule

Before a deployment process, someone copied a build to a server and hoped the service came back. If it failed,
the team had to remember which version had worked. A reliable deploy takes the tested artifact, starts it on the
target, shifts traffic, and checks the result. If the health check fails, it restores the last working version.
In this lesson, you'll deploy a static site and a server app, then plan a rollback before a bad release happens:

> **Figure.** The same deploy shape for three targets. Static site: upload the built folder to GitHub Pages, Netlify or a CDN; the new version replaces the old in one step; rollback is redeploying the previous build. Server over SSH: upload the release to releases/1.0.43, repoint the current symlink atomically, restart, health-check; if unhealthy, repoint current to the previous release and exit 1. Kubernetes: change the image in the Deployment; new pods start one at a time and replace old ones only after passing readiness; a broken image stalls the rollout while old pods keep serving, and kubectl rollout undo returns to the previous version.
>
> Get the tested artifact, put it in place, switch, prove it. If the proof fails, switch back automatically.

## Static sites

A static site (HTML, CSS, JavaScript, images) is the simplest deploy: upload the built folder. GitHub Pages
takes it straight from a workflow:

```yaml
name: Docs site

on:
  push:
    branches: [main]
    paths: ['docs/**']

permissions:
  contents: read

concurrency:
  group: pages
  cancel-in-progress: false

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - run: mkdir -p public && cp -r docs/* public/
      - uses: actions/upload-pages-artifact@v5
        with:
          path: public

  deploy:
    needs: build
    runs-on: ubuntu-latest
    permissions:
      pages: write
      id-token: write
    environment:
      name: github-pages
      url: ${{ steps.deployment.outputs.page_url }}
    steps:
      - id: deployment
        uses: actions/deploy-pages@v5
```

Set _Settings → Pages → Source_ to **GitHub Actions** once. For a real site, replace the `cp` with your build
(`npm run build`). Netlify, Vercel and Cloudflare Pages work the same way, and add a preview URL for every pull
request. This site is deployed exactly like that: previews on pull requests, staging from `main`, production from
a GitHub Release (the Git course's _Tags and releases_ lesson).

> **Video.** [Deploy to GitHub Pages — Automated Static Site CD Pipeline](https://www.youtube.com/watch?v=96FD1LSfSVE) (Backend Deep Dives)

## Deploy to a server over SSH

For an app on a Linux server, the safe pattern keeps every release in its own folder and points a `current`
symlink at the live one:

```text
/srv/shop-api/
├── releases/
│   ├── 1.0.42/
│   └── 1.0.43/        ← new
├── current -> releases/1.0.43
└── restart.sh         # sudo systemctl restart shop-api
```

This script uploads a release tarball, switches atomically, health-checks, and rolls back by itself:

```sh
#!/usr/bin/env bash
# Deploy a release tarball to a server over SSH, switch to it atomically, and roll back if it's unhealthy.
# usage: deploy-ssh.sh <user@host> <version> <tarball>
set -euo pipefail
host=${1:?usage: deploy-ssh.sh <user@host> <version> <tarball>}
version=${2:?version required}
tarball=${3:?tarball required}
ssh_opts=(-o BatchMode=yes ${SSH_PORT:+-p "$SSH_PORT"} ${SSH_KEY:+-i "$SSH_KEY"})
app=/srv/shop-api
health_url=${HEALTH_URL:-http://localhost:3000/health}

remote() { ssh "${ssh_opts[@]}" "$host" "$@"; }

echo "1. upload $version"
remote "mkdir -p $app/releases/$version"
ssh "${ssh_opts[@]}" "$host" "tar -xzf - -C $app/releases/$version" < "$tarball"

echo "2. switch current -> $version"
previous=$(remote "readlink $app/current || true")
remote "ln -sfn $app/releases/$version $app/current.new && mv -T $app/current.new $app/current && $app/restart.sh"

echo "3. health check"
for i in $(seq 1 10); do
  if remote "curl -fsS $health_url" > /dev/null 2>&1; then
    echo "   healthy: $(remote "curl -fsS $health_url")"
    remote "ls -1dt $app/releases/* | tail -n +6 | xargs -r rm -rf"   # keep the last 5 releases
    exit 0
  fi
  sleep 1
done

echo "4. unhealthy: rolling back to ${previous:-nothing}" >&2
if [[ -n $previous ]]; then
  remote "ln -sfn $previous $app/current.new && mv -T $app/current.new $app/current && $app/restart.sh"
fi
exit 1
```

Here it is against a test server: a good release, then one that crashes on start:

> **Figure.** A real terminal run of deploy-ssh.sh. Deploying 1.0.43: upload, switch current, health check, healthy with version 1.0.43, exit code 0. Deploying 1.0.44: upload, switch current, health check fails, rolling back to /srv/shop-api/releases/1.0.43, exit code 1.
>
> 1.0.43 goes live. 1.0.44 crashes, fails its health check, and the script puts 1.0.43 back by itself and exits 1, so CI turns red.

After the rollback, the app answered `{"status":"ok","version":"1.0.43"}` from outside the server. Users saw a
restart, not an outage.

| Detail                                                    | Why                                                              |
| --------------------------------------------------------- | ---------------------------------------------------------------- |
| `ln -sfn … current.new && mv -T current.new current`      | `mv` is one atomic rename: there's no moment without a `current` |
| keep the previous path before switching                   | the rollback target is known before anything changes             |
| restart through one script (`systemctl restart shop-api`) | the same command for deploys and rollbacks                       |
| `exit 1` after a rollback                                 | the pipeline goes red even though users are fine again           |
| keep the last 5 releases                                  | instant manual rollback further back, without filling the disk   |

> **Detach the restarted app from SSH.** If a restart starts the app in the background over SSH (`nohup node … &`), the SSH session waits for it and the deploy hangs. Redirect all three streams (`> app.log 2>&1 < /dev/null`) or, better, let systemd run the app (the Linux course's *Services with systemd* lesson), so the restart returns immediately.

### Running it from CI

```yaml
- name: Trust only our server's host key
  env:
    SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }}
    KNOWN_HOSTS: ${{ secrets.DEPLOY_KNOWN_HOSTS }}
  run: |
    install -d -m 700 ~/.ssh
    printf '%s\n' "$SSH_KEY" > ~/.ssh/id_ed25519 && chmod 600 ~/.ssh/id_ed25519
    printf '%s\n' "$KNOWN_HOSTS" > ~/.ssh/known_hosts
- name: Deploy
  run: ./scripts/deploy-ssh.sh deploy@shop.example.com "$VERSION" shop-api-*.tgz
```

Get `DEPLOY_KNOWN_HOSTS` once with `ssh-keyscan -t ed25519 shop.example.com`, check its fingerprint against the
server, and store it as a secret. Never use `StrictHostKeyChecking=no`: it hands your deploy key to whatever
machine answers. The deploy key belongs to a `deploy` user that can write `/srv/shop-api` and restart one service,
nothing else. Put the job behind the `production` environment with reviewers (lesson 4).

## Deploy to Kubernetes

> **Figure.** Animated. Three pods run version 1.0.42. After kubectl set image to 1.0.43, one new pod starts; only when it passes its readiness probe does an old pod stop. This repeats until all three run 1.0.43, with three pods ready the whole time. Then 1.0.44 is rolled out, but its first pod crashes on start and never becomes ready. The rollout stalls and the three 1.0.43 pods keep serving, until kubectl rollout undo removes the broken pod.
>
> One new pod at a time, and an old one stops only after the new one is Ready. A crashing release never takes traffic.

On Kubernetes, a deploy is changing the image of a **Deployment**. Kubernetes replaces pods gradually, and only
sends traffic to a new pod once its **readiness probe** passes:

```yaml
spec:
  replicas: 3
  progressDeadlineSeconds: 60
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxUnavailable: 0        # never fewer than 3 ready pods
      maxSurge: 1              # one extra new pod at a time
  template:
    spec:
      containers:
        - name: shop-api
          image: ghcr.io/elonerajeev/shop-api:1.0.42-e3b0c44
          readinessProbe:
            httpGet: { path: /health, port: 3000 }
```

```sh
$ kubectl set image deployment/shop-api shop-api=ghcr.io/elonerajeev/shop-api:1.0.43-9f2a1bc
$ kubectl rollout status deployment/shop-api --timeout=120s    # waits; exits non-zero if it fails
$ kubectl rollout history deployment/shop-api
$ kubectl rollout undo deployment/shop-api                     # back to the previous ReplicaSet
```

With `maxUnavailable: 0`, a broken image can't take the service down: its first new pod never becomes ready, the
rollout stops, and the three old pods keep serving. `rollout status` fails after `progressDeadlineSeconds`, which
fails the pipeline, and `rollout undo` cleans up. With GitOps (lesson 10), CI doesn't run `kubectl` at all: it
commits the new tag and Argo CD or Flux rolls it out the same way.

> **Video.** [Rollout and Rollback: How to Fix Failed Kubernetes Deployments-Live LAB Full CKA2026](https://www.youtube.com/watch?v=MiktPPwU8Jk) (CyberRavindra)

## Deployment strategies

Every deploy answers one question: **how many users see the new version, and how quickly?** The rolling update
above is one answer. There are three more, and teams mix them:

| Strategy         | Traffic on the new version | Roll back by                | Extra cost                | Watch out for                        |
| ---------------- | -------------------------- | --------------------------- | ------------------------- | ------------------------------------ |
| **Rolling**      | grows pod by pod           | another rollout, in minutes | one extra pod             | two versions serve at the same time  |
| **Blue/green**   | 0%, then 100%              | switching back, in seconds  | a second full environment | the shared database must suit both   |
| **Canary**       | a slice, then more         | setting its weight to 0     | a little                  | you need metrics to judge the canary |
| **Feature flag** | chosen users, in the code  | turning the flag off        | none in infrastructure    | old flags pile up as dead code       |

> **Figure.** Animated. Blue/green: users reach an nginx load balancer that sends every request to blue, running shop-api 1.0.43. Version 1.0.44 is started on the idle green environment and tested with no users. One nginx reload switches all traffic to green, and blue stays on standby for an instant rollback. Canary: starting again from blue, the load balancer is reloaded with weights 9 and 1, so 90 percent of requests go to 1.0.43 and 10 percent to the 1.0.44 canary. After checking error rates the split widens to 50 and 50, then 1.0.44 is promoted to all traffic.
>
> Blue/green moves everyone in one switch and keeps the old environment for rollback. A canary moves a slice at a time, so a bad release only reaches that slice.

### Rolling

The default on Kubernetes and most platforms, shown in the animation above: replace instances a few at a
time, each only after the new one is healthy. It costs almost nothing extra. The catch is that for a few
minutes **both versions serve requests**, so version 1.0.44 must not break clients or data that 1.0.43
still uses.

### Blue-green

Run two identical environments. One (blue) takes all traffic; deploy the new version to the idle one
(green), test it with no users on it, then repoint the load balancer. Rollback is the same switch backwards,
in seconds, because blue is still running. Here it is with three local nginx containers, `lb` in front:

```nginx
# conf/default.conf, mounted into the lb container
upstream shop_api {
    server blue:80;
}
server {
    listen 80;
    location / { proxy_pass http://shop_api; }
}
```

```sh
$ for i in 1 2 3; do curl -s localhost:8088; done
shop-api 1.0.43 (blue)
shop-api 1.0.43 (blue)
shop-api 1.0.43 (blue)
$ sed -i 's/server blue:80;/server green:80;/' conf/default.conf
$ docker exec lb nginx -s reload
$ for i in 1 2 3; do curl -s localhost:8088; done
shop-api 1.0.44 (green)
shop-api 1.0.44 (green)
shop-api 1.0.44 (green)
```

Mount the folder, not the single file: `sed -i` writes a new file, and a single-file bind mount keeps showing
the container the old one.

The price is a second environment, at least during the switch, and one hard rule: both colours share the
database, so a schema change must work for blue and green at once. On AWS the switch is usually an ALB
listener moving to another target group (CodeDeploy automates it for ECS); on Kubernetes, a Service whose
selector moves from `version: blue` to `version: green`.

### Canary

Send a small share of traffic to the new version, compare its errors and latency with the old one, then
widen in steps, or stop. The same containers, with weights:

```nginx
upstream shop_api {
    server blue:80  weight=9;    # stable, 1.0.43
    server green:80 weight=1;    # canary, 1.0.44
}
```

```sh
$ docker exec lb nginx -s reload
$ for i in $(seq 100); do curl -s localhost:8088; done | sort | uniq -c
     90 shop-api 1.0.43 (blue)
     10 shop-api 1.0.44 (green)
```

A canary is only as good as what you watch: the canary's error rate and latency **next to** the stable
version's, over enough requests to mean something. Weights split **requests**, not users, so one person can
bounce between versions; split by a cookie or user ID when that matters. Argo Rollouts and Flagger run the
steps and the checks for you on Kubernetes, and roll back on their own when a metric goes bad.

### Feature flags: deploy is not release

The strategies above move **traffic** between versions. A feature flag moves **behaviour** inside one
version: the new code ships switched off, and turning it on is the release. That lets you merge unfinished
work to main daily, turn a feature on for 1% of users, and turn it off in seconds without a deploy.

```js
// flags.js: same user, same answer every time
function isOn(name, userId) {
  const f = flags[name]
  if (!f || !f.enabled) return false
  const bucket = createHash('sha256').update(`${name}:${userId}`).digest().readUInt32BE(0) % 100
  return bucket < f.percent
}
```

```sh
$ cat flags.json
{ "new-checkout": { "enabled": true, "percent": 10 } }
$ node flags.js
new-checkout on for 101 of 1000 users
user-4 sees new checkout: true
$ sed -i 's/"percent": 10/"percent": 50/' flags.json
$ node flags.js
new-checkout on for 480 of 1000 users
user-4 sees new checkout: true
$ sed -i 's/"enabled": true/"enabled": false/' flags.json
$ node flags.js
new-checkout on for 0 of 1000 users
user-4 sees new checkout: false
```

Hashing the user ID keeps each user in the same bucket, so user-4, inside the first 10%, stays in as the
rollout widens to 50%. `enabled: false` is the kill switch. Real projects keep flags in a service
(LaunchDarkly, Unleash, or anything behind the OpenFeature standard) so they change without a deploy. Delete
a flag once it's fully on: every flag left behind is a code path nobody tests.

> **Video.** [Safe Deployment Strategies: Rolling, Blue-Green, Canary, and Rollback](https://www.youtube.com/watch?v=-VkgdzU4I_A&t=91s) (Joshua Moses | Cybertrace Foundation)

## Rollbacks: decide before you need one

| Deploy                   | Roll back by                                               | Time               |
| ------------------------ | ---------------------------------------------------------- | ------------------ |
| Static site              | redeploy the previous build, or revert and let CI redeploy | a minute           |
| Server, symlink releases | repoint `current` to the previous release, restart         | seconds            |
| Kubernetes               | `kubectl rollout undo`, or redeploy the previous tag       | a minute           |
| GitOps                   | `git revert` the tag change in the config repository       | a sync interval    |
| Database migration       | a forward fix: migrations rarely undo safely               | plan it in advance |

Two habits make rollbacks boring. **Keep each deploy reversible**: add a database column first, deploy code that
can use it, then remove the old column later. The previous app version can still work during that sequence.
Also **practise** on staging, so the recovery command is known before an incident.

A rollback changes the running version; it does not automatically undo data changes. Keep previous artifacts
available, know which command restores them, and check the service after the switch. For each target, test the
recovery path before an incident. If restoring the old version would break against the new schema, use a forward
fix or a planned migration instead of an unsafe reverse migration.

> **In production.** Deploy small changes often, behind the production environment's approval. Watch error rates for a few minutes after each deploy (the *Monitoring* course), and roll back first, investigate second. A deploy you can't undo in one command isn't finished.

## Mission: Deploy shop-api to a server, and survive a bad release

Package shop-api as a release tarball and deploy it to a Linux server with the SSH script: a good release, a second good one, then one that crashes on start. Prove the script rolled back by itself and that the app still answers.

- You need: A Linux VM you can SSH to as a deploy user, with Node 22 and curl; the shop-api repository
- You'll have: current pointing at the last good release, and a red exit code for the bad one

```sh
$ ssh deploy@<vm> 'mkdir -p /srv/shop-api/releases'
$ ssh deploy@<vm> 'cat > /srv/shop-api/restart.sh' <<'EOF'
#!/usr/bin/env bash
sudo systemctl restart shop-api
EOF
$ ssh deploy@<vm> 'chmod +x /srv/shop-api/restart.sh'
$ mkdir -p dist && cp -r src package.json dist/ && tar -czf shop-api-1.0.42.tgz -C dist .
$ cp shop-api-1.0.42.tgz shop-api-1.0.43.tgz
$ echo 'throw new Error("boom: missing config")' >> dist/src/server.js && tar -czf shop-api-1.0.44.tgz -C dist .
$ for v in 1.0.42 1.0.43 1.0.44; do ./scripts/deploy-ssh.sh deploy@<vm> $v shop-api-$v.tgz; echo "exit=$?"; done
$ ssh deploy@<vm> 'readlink /srv/shop-api/current && curl -s localhost:3000/health'
/srv/shop-api/releases/1.0.43
{"status":"ok","version":"1.0.43"}
```

The service unit (`/etc/systemd/system/shop-api.service`) runs `node /srv/shop-api/current/src/server.js` as the
`deploy` user, and a sudoers rule lets `deploy` run exactly `systemctl restart shop-api` (the Linux course's _Users
and groups_ and _Services_ lessons).

## Try it

- Publish a `docs/` folder to GitHub Pages with the workflow from this lesson.
- Run the deploy script against a test server twice, then with a broken release, and watch it roll back.
- Get your server's host key with `ssh-keyscan -t ed25519 <host>` and store it as a secret.
- List the releases on the server and switch `current` back by hand with `ln -sfn` and `mv -T`.
- On a test cluster, run `kubectl rollout status` during an update, then `kubectl rollout undo`.
- Write down, for your own app, the exact command that rolls back production.
- Run the blue/green and canary steps from this lesson with three nginx containers, and count where 100 requests land.

## Quiz

1. Why switch releases with a symlink instead of copying files over the running app?
   - Symlinks are faster to read
   - **Repointing current is one atomic step, so the app never runs half-copied files, and rollback is the same step backwards** (answer)
   - Copying is not allowed on Linux
   - It saves disk space
   Why: ln -sfn to a temporary name, then mv -T over current, swaps it in one rename. The previous release stays on disk for instant rollback.

2. What should a deploy script do when the new release fails its health check?
   - Exit 0 so the pipeline stays green
   - **Switch back to the previous release, restart it, and exit non-zero so CI shows red** (answer)
   - Delete the server
   - Wait for someone to notice
   Why: Users get the old working version back in seconds, and the red run tells the team something needs fixing.

3. Why store the server's host key in CI instead of using StrictHostKeyChecking=no?
   - It is faster
   - **Without it, CI would hand your deploy key and release to any machine that answers at that address** (answer)
   - GitHub requires it
   - SSH won't work otherwise
   Why: Pinning the known_hosts entry means a hijacked DNS name or IP fails the connection instead of receiving production.

4. A Kubernetes Deployment has maxUnavailable 0 and maxSurge 1. What happens if the new image crashes on start?
   - All pods are replaced and the app goes down
   - **One new pod fails readiness, the rollout stops, and the old pods keep serving** (answer)
   - Kubernetes rolls back by itself
   - The Deployment is deleted
   Why: New pods only replace old ones after passing the readiness probe. The rollout stalls (and reports failure after progressDeadlineSeconds); kubectl rollout undo returns to the previous ReplicaSet.

5. Which is a real rollback for a GitHub Pages static site?
   - Nothing can be rolled back
   - **Revert the commit and let the workflow redeploy, or redeploy an earlier run** (answer)
   - Delete the repository
   - Clear your browser cache
   Why: Static hosts serve whatever was deployed last. Netlify and Vercel can also republish an earlier deploy with one click.

6. A risky checkout change should reach about 5% of users first, so you can compare its error rate with the current version. Which strategy fits?
   - Blue/green
   - Stop the old version, start the new one
   - A rolling update with maxSurge 1
   - **Canary** (answer)
   Why: A canary sends a small, chosen share of traffic to the new version while the rest stays on the old one. Blue/green moves everyone at once; a rolling update moves pods, not a controlled share of users.

7. Your team wants to merge unfinished code to main every day without users seeing it. What makes that safe?
   - **A feature flag that keeps the new code path off in production** (answer)
   - A long-lived feature branch
   - Deploying only on Fridays
   - Blue/green
   Why: Deploy and release become separate steps: the code ships dark, and turning the flag on (for 1%, then everyone) is the release. Turning it off is the rollback.

## Resources

- [GitHub Docs: using custom workflows with GitHub Pages](https://docs.github.com/en/pages/getting-started-with-github-pages/using-custom-workflows-with-github-pages) (GitHub Docs)
- [GitHub Docs: using workflow_run to trigger a workflow](https://docs.github.com/en/actions/reference/workflows-and-actions/events-that-trigger-workflows#workflow_run) (GitHub Docs)
- [Kubernetes Docs: Deployments and rolling updates](https://kubernetes.io/docs/concepts/workloads/controllers/deployment/) (Kubernetes)
- [kubectl rollout reference](https://kubernetes.io/docs/reference/kubectl/generated/kubectl_rollout/) (Kubernetes)
- [ssh-keyscan(1) manual](https://manpages.ubuntu.com/manpages/noble/man1/ssh-keyscan.1.html) (Ubuntu manpages)
