Serving a simple Node app with NGINX

If not done so already, setup the vps and install node.

Create a simple Node app

Create a dir at the home dir called simple-server. Nav into the dir and init a new project.

cd ~
mkdir simple-server
cd simple-server
npm init -y

Make a new file called server.js

vim server.js

and copy the following code into it:

const http = require('http');

const server = http.createServer((req, res) => {
  const urlPath = req.url;
  if (urlPath === '/overview') {
    res.end('Welcome to the "overview page" of the nginX project');
  } else if (urlPath === '/api') {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(
      JSON.stringify({
        product_id: 'xyz12u3',
        product_name: 'NginX injector',
      })
    );
  } else {
    res.end('Successfully started a server');
  }
});

server.listen(3000, 'localhost', () => {
  console.log('Listening for request');
});

Write-quit (:wq)

Test it out by running the app

node server.js

And open a broswer and go to the server’s ip followed by :3000 to see if the app is working.

Add NGINX

It might be necessary to uninstall apache2. If you have problems with the steps below, see if removing apache2 helps. But first try skipping this step.

sudo apt-get remove apache2*

Install nginx

sudo apt update
sudo apt install nginx

Configure firewall

ufw is probably already installed. If it isn’t, install with

sudo apt install ufw

Allow ssh

ufw allow ssh

Allow nginx

sudo ufw allow 'Nginx HTTP'

If nginx is not running, start it

sudo systemctl start nginx

And check the status

sudo systemctl status nginx

Reverse Proxy

Add a config file to nginx available-sites

sudo vim /etc/nginx/available-sites/simple-server.config

And add the following code to the file.

server

{
        listen   80;
        server_name <server_ip_address>;

        location /  {
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header Host $host;
                proxy_set_header X-NginX-Proxy true;
                proxy_pass http://localhost:3000/;
                proxy_redirect http://localhost:3000/ https://$server_name/;
        }
}

Check that everything is okay with the nginx config files.

nginx -t

You might need to unlink and remove the default file from available-sites and enabled-sites.

Restart nginx

sudo systemctl restart nginx

Fire up the node app again and now the app should be running on port 80.

Keep the app always running with pm2

Install pm2

npm install pm2 -g

Then simply run the app with pm2 instead of node (may need to exit out of the node process if running).

pm2 start ~/simple-server/server.js

helpful articles: