← BACK TO INSIGHTS
TECH: DevOps & InfrastructureNOV 13, 2026•11 MIN READ•BY Anuj Bansal

Debugging Nginx 502 Bad Gateway with Next.js and PM2: A Production Post-Mortem and Prevention Guide

A practical DevOps post-mortem and diagnostic runbook for resolving intermittent Nginx 502 Bad Gateway errors when reverse proxying Next.js applications in PM2 cluster mode or Docker.

#Nginx#Next.js#PM2#DevOps#Linux Server Hardening#Reverse Proxy#502 Bad Gateway#Zero-Downtime Deployment
SHARE THIS ARTICLE:
DevOps & Infrastructure
💡Key Takeaways & Executive Summary
  • •An Nginx 502 Bad Gateway indicates that Nginx acting as a reverse proxy received an invalid response or connection drop from the upstream Next.js Node process.
  • •Inspect /var/log/nginx/error.log first: connect() failed (111: Connection refused) means Node crashed or is restarting; upstream prematurely closed connection indicates worker OOM or timeout.
  • •Avoid pm2 restart all in production which kills all cluster instances simultaneously; execute pm2 reload ecosystem.config.js --update-env for rolling zero-downtime reboots.
  • •Configure keepalive pools in Nginx upstream blocks and ensure Node keepAliveTimeout is greater than Nginx proxy read timeout to prevent race condition TCP resets.
  • •Use Unix domain sockets (/run/nextjs.sock) with strict chmod 660 for local reverse proxying to cut TCP stack latency by 15-25% over loopback 127.0.0.1:3000.

The Anatomy of an Nginx 502 Bad Gateway

In a production Linux deployment where Nginx serves as the reverse proxy in front of a Node.js / Next.js application, an HTTP 502 Bad Gateway does NOT mean your Nginx server is broken. It means Nginx successfully accepted the client HTTP/HTTPS request, but when it attempted to forward the request to the upstream application (e.g. http://127.0.0.1:3000 or a Unix socket), the upstream process failed to deliver a valid HTTP response.

The failure usually manifests intermittently during peak traffic spikes or right after a continuous integration deployment script runs. Here is the exact diagnostic sequence to find the root cause in minutes rather than guessing.


Step 1: The Diagnostic Log Audit

SSH into your production server and immediately inspect the Nginx error log:

bash
# Tail the most recent Nginx proxy errors
sudo tail -n 50 -f /var/log/nginx/error.log

You will typically observe one of three specific error signatures:

### Signature A: connect() failed (111: Connection refused) ``text 2026/11/13 14:22:10 [error] 18420#18420: *1204 connect() failed (111: Connection refused) while connecting to upstream, client: 203.0.113.45, server: anujbansaldev.in, request: "GET /services/nextjs-development HTTP/2.0", upstream: "http://127.0.0.1:3000/..." `` Root Cause: The Next.js process is not running or listening on that port. It either crashed due to an uncaught exception, was terminated by Linux kernel OOM killer, or is mid-reboot after a deploy.

### Signature B: upstream prematurely closed connection while reading response header ``text 2026/11/13 14:25:34 [error] 18420#18420: *1280 upstream prematurely closed connection while reading response header from upstream, client: 198.51.100.12, server: anujbansaldev.in... ` **Root Cause:** The Node process accepted the connection, started executing the request (e.g., rendering a heavy React tree or waiting on an unindexed MongoDB query), and was killed mid-execution because it exceeded memory limits (NODE_OPTIONS="--max-old-space-size=..."`) or timed out.


Step 2: The PM2 Reload vs Restart Trap

A frequent source of self-inflicted 502 errors during CI/CD deployments is executing pm2 restart ecosystem.config.js.

When you run pm2 restart, PM2 immediately kills all running Node worker threads simultaneously before compiling or launching the new processes. For the 4 to 12 seconds while Next.js boots up, every single incoming user request hitting Nginx receives an instant 502.

### The Production Fix: Rolling Zero-Downtime Reload Always use pm2 reload instead of restart. PM2 reload boots the new worker, waits for it to confirm listening, and only then terminates the old worker:

bash
# Zero-downtime rolling reload in production CI/CD
pm2 reload ecosystem.config.js --update-env

Here is a bulletproof ecosystem.config.js configuration:

javascript
// ecosystem.config.js
module.exports = {
  apps: [
    {
      name: 'portfolio-web',
      script: 'node_modules/next/dist/bin/next',
      args: 'start -p 3000',
      instances: 'max',
      exec_mode: 'cluster',
      max_memory_restart: '1G',
      listen_timeout: 10000,
      kill_timeout: 5000,
      wait_ready: true,
      env_production: {
        NODE_ENV: 'production',
        PORT: 3000,
      },
    },
  ],
}

Step 3: Upstream Keepalive and TCP Race Conditions

Another subtle bug causing intermittent 502s under load is the TCP keepalive timeout race condition between Nginx and Node.js.

By default, Nginx opens a new TCP connection for every upstream request unless a keepalive pool is specified. Furthermore, Node.js HTTP server has a default keepAliveTimeout of 5,000ms. If Nginx reuses a socket at the exact millisecond Node decides to close it, Node sends a TCP RST, and Nginx throws a 502 Bad Gateway.

### The Nginx Configuration Fix: ```nginx # /etc/nginx/conf.d/portfolio.conf

upstream nextjs_upstream { server 127.0.0.1:3000; keepalive 64; # Maintain open TCP connection pool }

server { listen 443 ssl http2; server_name anujbansaldev.in;

location / { proxypass http://nextjsupstream; proxyhttpversion 1.1; proxysetheader Connection ""; # Clear Connection header to enable keepalive proxysetheader Host $host; proxysetheader X-Real-IP $remoteaddr; proxysetheader X-Forwarded-For $proxyaddxforwardedfor; proxyset_header X-Forwarded-Proto $scheme;

# Resilient timeout bounds proxyconnecttimeout 60s; proxysendtimeout 60s; proxyreadtimeout 60s;

# Automatic retry on idempotent errors proxynextupstream error timeout invalidheader http502 http503; proxynextupstreamtries 3; } } ```

### The Next.js Node Server Fix: Ensure your Node server keepAliveTimeout is set higher than Nginx's proxy_read_timeout (e.g., 65,000ms vs 60,000ms). In custom Next.js servers:

javascript
const server = createServer((req, res) => handle(req, res))
server.keepAliveTimeout = 65000 // 65 seconds
server.headersTimeout = 66000   // 66 seconds
server.listen(3000)

Step 4: Upgrading from Loopback TCP to Unix Domain Sockets

For maximum security and performance on single-server VPS setups (e.g. Ubuntu 24.04 LTS), route traffic over Unix Domain Sockets instead of the network TCP loopback (127.0.0.1:3000). Unix sockets bypass the entire TCP/IP network stack, eliminating port exhaustion, context switching, and TCP handshake overhead:

nginx
upstream nextjs_upstream {
    server unix:/run/nextjs/portfolio.sock;
    keepalive 32;
}

With permissions set to chmod 660 owned by www-data:www-data, your application is completely unprobeable by external network port scanners.


Need Infrastructure Hardening or Deployment Automation?

If you are struggling with unpredictable server crashes, slow reverse proxies, or deployment downtime, explore our Linux Server Architecture & DevOps Optimization Service or request an infrastructure review through our Contact Form.

AB
ABOUT THE AUTHOR

Anuj Bansal

Anuj Bansal is a freelance full stack developer based in Indore, India specializing in scalable Next.js architectures, React web applications, Node.js backends, and high-performance server infrastructure. Looking to build a production-ready product? Hire Anuj for your next web application or SaaS platform.

🚀READY FOR PRODUCTION

Planning to Build a Production-Ready Web Application?

From system architecture and Next.js engineering to database optimization and technical SEO — let’s build a fast, scalable web product tailored to your business goals.

Available for New Projects⚡ Free 30-Min Architecture Discovery💬 Direct Engineering Access

Related Engineering Services

View All Services →

Need production implementation of these architectural patterns? Explore direct engineering capabilities:

Current: The Anatomy of an Nginx 502 Bad Gateway

Get engineering notes in your inbox.

Real-world lessons, system design deep-dives, and production stories — delivered weekly.