← All posts

Next.js deploys without 502: PM2 reload vs Kubernetes

Zero-downtime on a VPS: cluster mode, reload not restart, and why you should not delete .next mid-deploy.

Next.js deploys without 502: PM2 reload vs Kubernetes
Contents

In short

Every Next.js deploy on a VPS can mean a minute of 502 Bad Gateway — or not. A Habr walkthrough shows a PM2 recipe: reload instead of restart, cluster mode, and sane handling of the .next build output.

What happened

The author describes a familiar loop: push to main, CI builds, pm2 restart on the server — nginx serves 502 while the process is down. The issue is common for teams without Kubernetes.

Two frequent mistakes:

  1. pm2 restart — the process exits, the port is empty, users see 502.
  2. Deleting .next on a live server before next build finishes — the app has nothing to serve mid-build.

The fix is pm2 reload in cluster mode: PM2 starts new workers, then drains old ones (zero-downtime at the Node layer).

Why it matters

For small and medium traffic, VPS + PM2 is often cheaper and faster to operate than a Kubernetes cluster — but only if reload is configured correctly.

Approach Pros Cons
PM2 on VPS Simple CI, few moving parts You own SSL, backups, scaling
Kubernetes Rolling updates, autoscaling Complexity and cost for a single app

In practice

  1. Run Next in cluster mode (instances: max or a fixed worker count).
  2. After build in CI/CD, run pm2 reload ecosystem.config.cjs, not restart.
  3. Build .next in CI or a staging dir; do not rm -rf .next under a live process.
  4. Point nginx health checks at the upstream after reload.

Takeaway

502 on deploy is usually a release-process bug, not a Next.js curse. For many VPS setups, PM2 reload plus disciplined builds is enough; reach for Kubernetes when resilience and scale requirements grow.