Zero-Downtime Node.js Deploys on a VPS: GitHub Actions + PM2 (Rollback <60s)

Published · Updated

Zero-Downtime Node.js Deploys on a VPS: GitHub Actions + PM2 (Rollback <60s)

The usual “SSH in, git pull, pm2 restart” deploy drops requests every time: restart kills all workers at once, npm install rewrites node_modules under a running app, and if the new code is broken there’s no quick way back.

This guide replaces it with a pipeline that a single VPS handles fine — no Docker or Kubernetes needed:

  1. GitHub Actions tests and builds the app, then uploads a tarball.
  2. The VPS unpacks it into a new release folder and installs dependencies there.
  3. A current symlink is atomically switched to the new release.
  4. PM2 reloads workers one at a time, each signalling when it’s ready.
  5. A health check confirms the new release is actually serving — and rolls back automatically if not.

It assumes you already have Node.js under PM2 behind Nginx. If not, set that up first: Node.js VPS guide, Nginx reverse proxy config, PM2 cluster config. Nginx needs no changes during deploys — it keeps proxying to 127.0.0.1:3000 the whole time.


Step 1: Release Folder Layout on the VPS

sudo mkdir -p /var/www/myapp/{releases,shared}
sudo chown -R deploy:deploy /var/www/myapp
# put production secrets here once; every release links to it
nano /var/www/myapp/shared/.env
/var/www/myapp
├── releases/
│   ├── 20261105-091500-a1b2c3d/
│   └── 20261105-143000-e4f5a6b/
├── shared/
│   └── .env
└── current -> releases/20261105-143000-e4f5a6b

Each release has its own node_modules. That costs some disk, but it’s what makes rollback instant: the previous release is still fully installed, so going back is just a symlink switch and a reload. Release names start with a UTC timestamp so they sort chronologically.


Step 2: Make the App Reload-Safe

PM2’s reload only gives zero downtime if the app cooperates. Three small changes:

// server.js
const server = app.listen(process.env.PORT || 3000, "127.0.0.1", () => {
  // Tell PM2 this worker is ready to receive traffic
  if (process.send) process.send("ready");
});

// PM2 sends SIGINT when replacing a worker: stop accepting new
// connections, let in-flight requests finish, then exit.
process.on("SIGINT", () => {
  server.close(() => process.exit(0));
  setTimeout(() => process.exit(1), 4000).unref(); // hard stop before kill_timeout
});

// Health check that reports WHICH release is running
app.get("/healthz", (req, res) => {
  res.json({ status: "ok", release: process.env.RELEASE_ID });
});

And the matching ecosystem.config.cjs, committed in the repo:

module.exports = {
  apps: [{
    name: "myapp",
    script: "dist/server.js",
    cwd: "/var/www/myapp/current",
    exec_mode: "cluster",
    instances: 2,
    wait_ready: true,      // wait for process.send("ready")
    listen_timeout: 10000, // give up waiting after 10s
    kill_timeout: 5000,    // time allowed for graceful shutdown
    env: { NODE_ENV: "production", PORT: 3000 },
  }],
};

Why each piece matters:

  • exec_mode: "cluster" — in fork mode, pm2 reload behaves like restart and you get a gap.
  • wait_ready + process.send("ready") — without it PM2 considers a worker ready as soon as the process starts, before it’s listening, and kills the old worker too early.
  • Graceful SIGINT handler — without it, requests in flight on the old worker are cut off.
  • release in /healthz — a plain “ok” health check passes even when the old code is still running. Checking the release ID proves the deploy actually took effect.

Step 3: The Remote Deploy Script

Keep this in the repo as scripts/remote-deploy.sh. GitHub Actions pipes it to the server, so it’s versioned with your code:

#!/usr/bin/env bash
set -euo pipefail

APP_DIR="$1"
RELEASE="$2"
RELEASE_DIR="$APP_DIR/releases/$RELEASE"
PREVIOUS="$(readlink -f "$APP_DIR/current" || true)"

# Non-interactive SSH doesn't load ~/.bashrc, so nvm-installed node/pm2
# aren't on PATH. Load nvm explicitly (skip if Node came from apt/NodeSource).
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"

mkdir -p "$RELEASE_DIR"
tar -xzf "/tmp/$RELEASE.tar.gz" -C "$RELEASE_DIR"
rm -f "/tmp/$RELEASE.tar.gz"

cd "$RELEASE_DIR"
npm ci --omit=dev --no-audit --no-fund
ln -sfn "$APP_DIR/shared/.env" "$RELEASE_DIR/.env"

# Run migrations here, BEFORE switching (see "Database migrations" below)
# npm run migrate

switch_to() {
  # ln -sfn is unlink+create (a brief moment with no symlink).
  # Creating a temp link and renaming it over `current` is atomic.
  ln -sfn "$1" "$APP_DIR/current.tmp"
  mv -Tf "$APP_DIR/current.tmp" "$APP_DIR/current"
  cd "$APP_DIR/current"
  RELEASE_ID="$(basename "$1")" pm2 startOrReload ecosystem.config.cjs --update-env
}

healthy() {
  for _ in $(seq 1 15); do
    if curl -fsS --max-time 3 http://127.0.0.1:3000/healthz | grep -q "\"release\":\"$1\""; then
      return 0
    fi
    sleep 2
  done
  return 1
}

switch_to "$RELEASE_DIR"

if ! healthy "$RELEASE"; then
  echo "New release failed health check — rolling back to $PREVIOUS" >&2
  if [ -n "$PREVIOUS" ]; then
    switch_to "$PREVIOUS"
  fi
  exit 1
fi

pm2 save
# keep the 5 newest releases
ls -1d "$APP_DIR"/releases/*/ | sort -r | tail -n +6 | xargs -r rm -rf
echo "Deployed $RELEASE"

The health check retries for up to 30 seconds because reload replaces workers one at a time — for a few seconds both old and new releases are serving.


Step 4: The GitHub Actions Workflow

One-time setup:

  1. Create a deploy key pair locally: ssh-keygen -t ed25519 -f deploy_key -N "". Append deploy_key.pub to /home/deploy/.ssh/authorized_keys on the VPS.
  2. Capture the server’s host key from a machine you trust: ssh-keyscan -H YOUR_SERVER_IP.
  3. Add repository secrets: VPS_HOST, VPS_USER (deploy), VPS_SSH_KEY (contents of deploy_key), VPS_KNOWN_HOSTS (output of step 2).

Storing the host key as a secret, instead of running ssh-keyscan inside the workflow, means a spoofed server can’t silently receive your deploy.

.github/workflows/deploy.yml:

name: Deploy

on:
  push:
    branches: [main]
  workflow_dispatch:

concurrency:
  group: production-deploy
  cancel-in-progress: false   # never interrupt a deploy halfway

jobs:
  deploy:
    runs-on: ubuntu-latest
    environment: production
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm

      - run: npm ci
      - run: npm test
      - run: npm run build

      - name: Package release
        run: |
          echo "RELEASE=$(date -u +%Y%m%d-%H%M%S)-${GITHUB_SHA::7}" >> "$GITHUB_ENV"
          tar -czf release.tar.gz dist package.json package-lock.json ecosystem.config.cjs

      - name: Configure SSH
        run: |
          install -m 700 -d ~/.ssh
          echo "${{ secrets.VPS_SSH_KEY }}" > ~/.ssh/deploy_key
          chmod 600 ~/.ssh/deploy_key
          echo "${{ secrets.VPS_KNOWN_HOSTS }}" > ~/.ssh/known_hosts

      - name: Upload and deploy
        env:
          TARGET: ${{ secrets.VPS_USER }}@${{ secrets.VPS_HOST }}
          APP_DIR: /var/www/myapp
        run: |
          scp -i ~/.ssh/deploy_key release.tar.gz "$TARGET:/tmp/$RELEASE.tar.gz"
          ssh -i ~/.ssh/deploy_key "$TARGET" "bash -s -- '$APP_DIR' '$RELEASE'" < scripts/remote-deploy.sh

A common mistake in deploy workflows is writing the remote commands inline in a quoted heredoc (ssh host << 'EOF'). Variables like $APP_DIR are then evaluated on the server, where they don’t exist, and with set -u the deploy aborts. Passing them as arguments to bash -s, as above, avoids that.

The environment: production line lets you add required reviewers or a branch restriction under Settings → Environments if you want a manual approval gate.


Step 5: Database Migrations Without Breaking Rollback

Rollback switches the code back, not the database. If a migration drops or renames a column, the previous release crashes against the new schema and rollback makes things worse.

Use the expand / contract pattern:

Deploy Schema change Code
1 (expand) Add new column/table; keep the old one Writes both, reads old
2 Backfill data Reads new
3 (contract) Drop the old column Uses only new

Every individual deploy is then compatible with the release before it, so rollback is always safe. Run migrations in remote-deploy.sh before switch_to — if a migration fails, set -e stops the deploy while the old release is still serving.


Rollback in Under 60 Seconds

The automatic rollback covers failed health checks. For problems you notice later (wrong behaviour, not a crash), roll back manually. Since every release is still installed, this is just a switch and a reload:

APP_DIR=/var/www/myapp
CURRENT=$(readlink -f "$APP_DIR/current")
TARGET=$(ls -1d "$APP_DIR"/releases/*/ | sed 's:/$::' | sort | grep -x -B1 "$CURRENT" | head -1)
[ "$TARGET" != "$CURRENT" ] || { echo "no older release"; exit 1; }

ln -sfn "$TARGET" "$APP_DIR/current.tmp" && mv -Tf "$APP_DIR/current.tmp" "$APP_DIR/current"
cd "$APP_DIR/current"
RELEASE_ID="$(basename "$TARGET")" pm2 startOrReload ecosystem.config.cjs --update-env
curl -fsS http://127.0.0.1:3000/healthz

Then revert the bad commit on main, so the next push doesn’t redeploy it.


Troubleshooting

Symptom Cause Fix
pm2: command not found / npm: command not found in the deploy log Non-interactive SSH doesn’t load nvm from ~/.bashrc Source nvm.sh in the script (already done above)
Health check fails: release ID doesn’t match Old code still running — pm2 reload myapp without the ecosystem file, or missing --update-env Always reload via ecosystem.config.cjs with --update-env
Brief 502s during deploy Fork mode, restart instead of reload, or no wait_ready Cluster mode + Step 2
Every deploy takes ~10s per worker wait_ready: true but app never calls process.send("ready") — PM2 waits for listen_timeout Add the ready signal
Host key verification failed Server rebuilt or IP reused; VPS_KNOWN_HOSTS is stale Re-run ssh-keyscan and update the secret
Permission denied (publickey) Deploy key not in authorized_keys, or wrong user Check ~/.ssh/authorized_keys of VPS_USER; permissions 700 on .ssh, 600 on the file
Disk filling up Old releases or npm cache The prune line keeps 5 releases; npm cache clean --force occasionally
502 after deploy, health check passed Nginx problem, not deploy See the Nginx troubleshooting table

FAQ

Is pm2 reload really zero downtime?

In cluster mode with a ready signal and graceful shutdown, yes — PM2 starts a new worker, waits for ready, then sends SIGINT to an old one, one at a time. Long-lived WebSocket connections on an old worker will be closed and must reconnect; clients like Socket.io do that automatically.

Does this work on a 1 vCPU VPS?

Yes. Use instances: 2 anyway — two workers on one core cost a little extra RAM, and they guarantee there’s always a worker serving during the reload. Check your memory budget in the PM2 guide.

Why not build on the server instead of in GitHub Actions?

Building on a small VPS competes with the running app for CPU and RAM, and a failed build leaves you half-deployed. Building in CI means the server only unpacks and installs production dependencies.

Do I need Docker for this?

No. Docker gives you reproducible images, but for one Node.js app on one VPS, release folders plus PM2 give the same deploy and rollback behaviour with less to maintain.