How To Serve NodeJS App Behind a Nginx Server in Ubuntu

Nginx is one of the robust webservers and it can be used as a reverse proxy for your nodejs apps. In this article, We will setup Nginx and use it to serve node app.
NGINX installation :
- Update packages using sudo apt-get update
- Install Nginx using command sudo apt-get install nginx
- Now, Check the status of Nginx server using command systemctl status nginx. You can see that the server is started and active.
4. Open Browser and navigate to localhost:80, You can see Nginx welcome screen.
By Default, Nginx starts automatically when your system boots. Now , let us see some basic commands to use Nginx.
To start the Nginx server : sudo systemctl start nginx
To stop your Nginx server : sudo systemctl stop nginx
To restart Nginx server : sudo systemctl restart nginx
To disable automatic start of Nginx server when your system boots :
sudo systemctl disable nginx
To re-enable Nginx server : sudo systemctl enable nginx
Serve NodeJS App Through Nginx:
Let us create a simple node app that runs on port 3010 and serves a welcome page. The entry point app.js is as shown below.
The template file is as shown below
Now , one can start the node app and access it at localhost:3010. But, our aim is to run it behind Nginx. So, let us configure Nginx.
Nginx Configuration:
1. Go to /etc/nginx/sites-available/
2. Open default file and configure "proxy_pass" to "localhost:3010" for "location /"
3. Now restart the Nginx server by using the command
sudo systemctl restart nginx
4. Open browser and navigate to localhost, We can see now that our node app is being served.

Configure Multiple Apps Through Nginx:
It's time to configure our Nginx to serve multiple NodeJS Apps. Now let us create another node app which runs at “localhost:3011/blog” by making simple code changes to the above node app.
Add the new node app url "localhost:3011/blog" to the “default” file as a new "location /blog" as shown in below picture.
Now restart the Nginx server and check “/blog” route in Nginx default port.
