Home >Web Front-end >JS Tutorial >How to set up Nginx as a front-end server for Node.js
nginx is a powerful and widely used tool for web servers. It also serves as a front-end proxy server for multiple web application servers. This article will introduce you to setting up an Nginx server as a front-end proxy server for a Node.js application.
1. Install node.js
First install the required software packages for node.js installation and install them on the launchpad Add available nodejs PPA. After that use the following command to install nodejs.
$ sudo apt-get install python-software-properties python g++ make $ sudo add-apt-repository ppa:chris-lea/node.js $ sudo apt-get update $ sudo apt-get install nodejs
2. Install nginx
Now use apt get to install the nginx web server. nginx is available under the default repository.
$ sudo apt-get install nginx
3. Create a test node server
Now create a test node server application and run it on port 3000 of host 127.0.0.1. To create a node server, create the file ~/myapp/myapp.js.
$ cd ~/MyApp/ $ vi myapp.js
And 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 Worldn'); }).listen(3000, "127.0.0.1"); console.log('Server running at http://127.0.0.1:3000/');
Now use the following command to start nodejs in the background
$ node myapp.js &
Access in the browser.
Output: Hello Word
4. Configure NGNIX
After starting the demo server using node.js, now start using Nginx for configuration. Create a virtual host configuration file for the domain in the /etc/nginx/conf.d/ directory.
$ sudo vim /etc/nginx/conf.d/example.com.conf
and add the following.
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 completing all configurations, let us restart the nginx web server using the following command.
$ sudo /etc/init.d/nginx restart
5. Verify the installer
Now access your server using the domain name, you will see the same at http://127.0.0.1:3000/ page.
Output is Hello Word
This article has ended here. For more other exciting content, you can pay attention to the node.js video tutorial column of the PHP Chinese website ! ! !
The above is the detailed content of How to set up Nginx as a front-end server for Node.js. For more information, please follow other related articles on the PHP Chinese website!