How to Setup Nginx as Frontend Server for Node.js
Abstract: and add the following content. #Setup upstream for backend Node.js serverStep 4 – Configure NGINX After starting a demo server with node.js. Now start
Nginx is powerful and widely used for the webserver. It also used as a frontend proxy server for multiple web application servers runs behind this. This tutorial will help you to set up your Nginx server as a frontend proxy server for your Node.js application.
Step 1 – PrerequsitiesWe are assuming you have pre-installed Node.js on your system. But still, if you want to install Node.js follow this tutorial.
Step 2 – Create Sample Node ApplicationAs you are here ? You must be running your Node application on some port. We assume your application is running on port 3000. So for the demonstration, I am creating a sample web application on Node.js and run on port 3000. So it will be easier to understand for you.
If you don’t have running application, You can also follow below instruction to run a sample web application. So, create a JavaScript file and edit in your favorite text editor.
vi myapp.js
Then, add the following content in the javascript file.
var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World'); }).listen(3000, "127.0.0.1"); console.log('Server running at http://127.0.0.1:3000/');
Your Node application is ready to serve on port 3000. Let’s start the Node.js application in the background.
node myapp.js &
And access this in the browser. You will see the result like below:
Step 3 – Install NginxNow install the Nginx web server using the default Package manager. The Ubuntu and Debian based systems use apt, Fedora and CentOS/RHEL 8 use DNF and CentOS/RHEL 7/6 uses yum. Nginx is available under default repositories on almost operating systems.
Step 4 – Configure NGINXsudo apt install nginx
### Debians based systemssudo yum install nginx
### CentOS 7/6sudo dnf install nginx
### Fedora & CentOS 8
After starting a demo server with node.js. Now start configuration with Nginx. Create a virtual host configuration file for your domain under /etc/nginx/conf.d/ directory.
sudo vim /etc/nginx/conf.d/example.com.conf
and add the following content.
#Setup upstream for backend Node.js server upstream myapp { server 127.0.0.1:3000; keepalive 8; } #The Nginx server instance server { listen 0.0.0.0:80; server_name example.com www.example.com; access_log /var/log/nginx/example.com.log; location / { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header X-NginX-Proxy true; proxy_pass http://myapp/; proxy_redirect off; } }
After creating the configuration, restart Nginx web server using following command.
sudo systemctl restart nginx
Step 5 – Verify Setup
Now access your server using domain name, you will see the same page shows on http://127.0.0.1:3000/ .