πŸŒ€ Setting Up NGINX as a Reverse Proxy for a Node.js App(Simple End-to-End Guide)

Want to run your Node.js app behind NGINX like a pro? Here’s a simple, step-by-step guide to help you get it done smoothly—from setting up Node.js to routing traffic through NGINX.

πŸ”§ What You'll Set Up

A simple Node.js app running on localhost:3000

NGINX forwarding requests from http://yourdomain.com to your Node.js app

(Optional) HTTPS with a free SSL certificate from Let's Encrypt







πŸ“¦ Prerequisites

A Linux server (Ubuntu/Debian)

Domain name pointed to your server’s IP

Root or sudo access


πŸš€ Step 1: Install Node.js & Build a Sample App


✅ Install Node.js


sudo apt update

sudo apt install nodejs npm -y

πŸ›  Create Your App

mkdir ~/myapp

cd ~/myapp

vi  index.js


Paste this code:


const http = require('http');

const server = http.createServer((req, res) => {

  res.end('Hello from Node.js!');

});

server.listen(3000, () => {

  console.log('Server running on http://localhost:3000');

});



▶️ Run It

node index.js

You can now visit:

http://localhost:3000 → See: Hello from Node.js!


Keep this running or use a process manager like PM2 for production:

sudo npm install -g pm2

pm2 start index.js

pm2 startup

pm2 save


🌐 Step 2: Install NGINX


sudo apt install nginx -y

Start and enable NGINX:

sudo systemctl start nginx

sudo systemctl enable nginx



πŸ” Step 3: Configure NGINX as a Reverse Proxy

Create a config file:

sudo vi /etc/nginx/sites-available/myapp



Paste this:

server {

    listen 80;

    server_name yourdomain.com;

    location / {

        proxy_pass http://localhost:3000;

        proxy_http_version 1.1;

        proxy_set_header Upgrade $http_upgrade;

        proxy_set_header Connection 'upgrade';

        proxy_set_header Host $host;

        proxy_cache_bypass $http_upgrade;

    }

}



## To exit editor = PRESS esc AND :wq!

Enable the config:

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


To unlink default folder
sudo unlink /etc/nginx/sites-enabled/default


Test and reload:

sudo nginx -t

sudo systemctl reload nginx

Now visit:

πŸ“‘ http://yourdomain.com → You should see "Hello from Node.js!"


πŸ”’ Step 4: (Optional) Add HTTPS with Let's Encrypt

Install Certbot:

sudo apt install certbot python3-certbot-nginx -y

Run:

sudo certbot --nginx -d yourdomain.com


Certbot will:


Get the SSL certificate

Automatically configure NGINX

Set up HTTPS for you


Auto-renewal:

sudo systemctl status certbot.timer




🧠 Final Tips

Restart your app with pm2 restart all if needed

Check NGINX logs: sudo tail -f /var/log/nginx/access.log

Use firewalls (ufw) to only expose ports 80 and 443


Comments

Popular posts from this blog

Basic Monitoring and Logging for DevOps Beginners

AWS vs. Azure vs. GCP: Which Cloud Should a DevOps Beginner Learn First