π 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:
Comments
Post a Comment