Reverse proxy is the recommended way to let your audience access your nodejs app. Never expose the application ports directly to the end users. Also, use a firewall like UFW to block all ports except 80 (http), 443 (https) and your SSH port with limited access.
Creating NodeJs Hello World App
Skip this step if you have already a running app.
Create your app directory.
mkdir helloworld
cd helloword
Init npm and Install Express. Leave all the options as default on npm init prompts.
npm init
npm install express --save
Create the index.js file and put the below sample content (/helloword/index.js)
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(3001, function () {
console.log('Hello app listening on port 3001!');
});
Now run the app
node index.js
Check your app is accessible in localhost in the specified port. For Example: 3001
You can check it using curl in the console.
curl http://localhost:3001
Configure DNS
Add A record in your DNS Hosting Manager (Access your Domain Control Panel or DNS Hosting account like Cloudflare) For example :
A example.com 14400
Configure Nginx
Create a server block, replace example.com with your domain
sudo nano /etc/nginx/sites-available/example.com
Add the below content by replacing the example.com with your domain and update the port address to match your application port address.
server {
listen 80;
listen [::]:80;
server_name example.com;
location / {
proxy_pass http://localhost:3001;
include proxy_params;
}
}
Enable the site in Nginx
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
Test the Nginx server blocks configuration
sudo nginx -t
If you see the following message, the syntax is correct
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
Now restart the nginx service
sudo systemctl restart nginx
Now you can access your website on the Browser and see the output
Hello World!