Help CenterVPS & CloudHow do I set up Nginx as a reverse proxy for my Node.js app?

How do I set up Nginx as a reverse proxy for my Node.js app?

Serve your Node.js app on a domain with Nginx, then add a free SSL certificate.

What this does

Nginx receives web traffic on ports 80 and 443 and passes it to your Node.js app, which listens on a local port such as 3000. Nginx also handles SSL.

Before you start

  • Your app is running, for example with PM2, on port 3000.
  • Your domain's A record points to your VPS IP address.
  • Ports 80 and 443 are allowed in your firewall.

Step 1: Install Nginx

sudo apt update

sudo apt install nginx -y

Step 2: Create the site file

Create /etc/nginx/sites-available/myapp. Set server_name to your domain. Inside a location / block, add proxy_pass http://127.0.0.1:3000; and set the headers Host, X-Real-IP, X-Forwarded-For and X-Forwarded-Proto.

Step 3: Enable it and reload

sudo ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled/

sudo nginx -t

sudo systemctl reload nginx

If nginx -t reports an error, fix the line it points to before reloading.

Step 4: Add free SSL

sudo apt install certbot python3-certbot-nginx -y

sudo certbot --nginx -d example.com -d www.example.com

Choose the option to redirect HTTP to HTTPS. Certificates renew automatically.

Troubleshooting

  • 502 Bad Gateway usually means your app is not running or is on a different port.
  • Check logs with sudo tail -f /var/log/nginx/error.log.

Need help?

If you get stuck, open a support ticket or email info@webzworld.com and our team will help.

Was this article helpful? Contact Support