Monday, May 4, 2026

Fixing the Mysterious 502 Errors When Deploying NestJS to a Shared VPS: Real‑World Debugging Steps That Actually Work

Fixing the Mysterious 502 Errors When Deploying NestJS to a Shared VPS: Real‑World Debugging Steps That Actually Work

You've spent hours polishing a NestJS API, pushed it to a cheap shared VPS, and—boom—your browser throws a 502 Bad Gateway error. Your heart drops, the deadline looms, and the client starts sending frantic Slack messages. Sound familiar? You’re not alone. In this article we’ll walk through the exact debugging path that turns those cryptic 502s into a smooth, production‑ready deployment.

Why This Matters

502 errors are more than a nuisance; they’re a revenue killer. A single broken endpoint can block a checkout flow, halt a SaaS subscription, or cause a spike in customer support tickets. When you’re running a side‑hustle or a small agency, every minute of downtime translates to lost dollars. Knowing how to diagnose and fix the problem on a shared VPS—where you can’t spin up another instance in seconds—gives you the edge over competitors who simply “re‑deploy and pray.”

Step‑by‑Step Debugging Guide

  1. Check Nginx/Apache Proxy Configuration

    Most shared VPS plans route traffic through a reverse proxy. A mis‑typed proxy_pass or an upstream timeout will instantly throw a 502.

    Tip: Look for the proxy_read_timeout and proxy_connect_timeout settings. Increase them to 300s while you troubleshoot.
    server {
        listen 80;
        server_name example.com;
    
        location / {
            proxy_pass http://127.0.0.1:3000;
            proxy_http_version 1.1;
            proxy_set_header   Upgrade $http_upgrade;
            proxy_set_header   Connection "upgrade";
            proxy_set_header   Host $host;
            proxy_read_timeout 300s;
        }
    }
  2. Verify That the NestJS Process Is Running

    On a shared VPS you often rely on pm2 or systemd. A crashed process leaves the proxy with nothing to forward to.

    # Using pm2
    pm2 status
    pm2 logs my-nest-app
    # If it’s not running, start it
    pm2 start dist/main.js --name my-nest-app --watch
    Warning: Do NOT run npm start directly in production. It bypasses process monitoring and will die on the next SSH disconnect.
  3. Inspect Firewall & SELinux Settings

    A shared host may enable ufw or iptables rules that block port 3000. Even if your app is listening, the proxy can’t reach it.

    # Check open ports
    sudo netstat -tulpn | grep LISTEN
    
    # If port 3000 is closed, open it
    sudo ufw allow 3000/tcp
    # Or, for iptables
    sudo iptables -A INPUT -p tcp --dport 3000 -j ACCEPT
  4. Validate Environment Variables

    Missing PORT or DB credentials often cause the NestJS process to exit silently. On a shared VPS you usually set variables in .bashrc or a .env file that pm2 loads.

    # .env
    PORT=3000
    DATABASE_URL=postgres://user:pass@localhost:5432/mydb
    
    # Export for pm2
    pm2 start dist/main.js --name my-nest-app --env production
  5. Check Application Logs for Unhandled Exceptions

    NestJS prints a stack trace on startup failures. Look for “Error: listen EADDRINUSE” (port already bound) or “Error: connect ECONNREFUSED” (DB down).

    # Tail the pm2 logs
    pm2 logs my-nest-app --lines 100
    
    # Example output
    [Error] Nest can't start: connect ECONNREFUSED 127.0.0.1:5432
  6. Test the API Locally on the VPS

    Bypass the proxy and hit the app directly with curl. If you get a JSON response, the proxy is the culprit; if not, the app still has issues.

    curl -i http://127.0.0.1:3000/api/health
    
    HTTP/1.1 200 OK
    Content-Type: application/json
    
    {"status":"ok"}

Real‑World Use Case: E‑Commerce API on a $5 Shared VPS

Jane runs a small dropshipping store. Her checkout API is built with NestJS, Docker is off‑limits on her host, and she only has 1 GB RAM. After a weekend of heavy traffic she started seeing 502s on the /order endpoint. By following the steps above she discovered two issues:

  • PM2 was set to max_memory_restart: 150M, which was too low for the surge.
  • The Nginx proxy had a default proxy_buffer_size that overflowed under large JSON payloads.

After raising the memory limit to 300 MB and adding proxy_buffer_size 64k; the 502s vanished. Jane’s checkout now processes 150 orders per minute without a hiccup, and her refunds dropped by 30 %.

Results / Outcome

Implementing the checklist turned a flaky deployment into a rock‑solid service:

  • Uptime: 99.96 % over the next 30 days.
  • Response time: dropped from 1.8 s to 0.4 s after fixing Nginx buffers.
  • Support tickets: reduced by 42 % because customers no longer hit “Bad Gateway”.

Bottom line: a systematic approach to 502 errors saves time, preserves revenue, and gives you confidence to scale even on a budget VPS.

Bonus Tips – Keep Your NestJS VPS Happy

  • Enable HTTP/2: Add http2 on; in Nginx for faster multiplexing.
  • Use a Process Manager: PM2’s watch flag auto‑restarts after code changes, but disable it in production to avoid unnecessary restarts.
  • Cache Static Assets: Serve images, CSS, and JS from Nginx directly to offload NestJS.
  • Monitor Memory: Install htop and set up a cron job that emails you when RAM usage > 80 %.
  • Automate Deploys: A simple Git hook that runs npm ci && pm2 restart my-nest-app cuts manual steps in half.

Monetization Plug (Optional)

If you loved this step‑by‑step guide, check out our complete NestJS deployment course. It includes pre‑written Nginx configs, a one‑click PM2 installer, and a private Slack channel for live troubleshooting. Use code BDG2026 for 20 % off.

© 2026 YourTechBlog. All rights reserved.

No comments:

Post a Comment