Setup Node.js and Nginx on the Server
How does Node.js and Nginx work together on server?
Nginx works as a front end server, which in this case proxies the requests to a node.js server. Therefore we need to setup an nginx config file for node.
This is how I have done in Unbuntu:
Create the file yourdomain
at /etc/nginx/sites-available/
:
vim /etc/nginx/sites-available/yourdomain
In it you should have somethign like:
# the IP(s) on which your node server is running. I chose port 3000.
upstream app_yourdomain {
server 127.0.0.1:3000;
keepalive 8;
}
# the nginx server instance
server {
listen 0.0.0.0:80;
server_name yourdomain.com yourdomain;
access_log /var/log/nginx/yourdomain.log;
# pass the request to the node.js server with the correct headers
# and much more can be added, see nginx config options
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://app_yourdomain/;
proxy_redirect off;
}
}
If you want nginx (>= 1.3.13) to handle websocket requests as well, add the following lines in the location /
section:
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
Once you have this setup you must enable the site defined in the config file above:
cd /etc/nginx/sites-enabled/
ln -s /etc/nginx/sites-available/yourdomain yourdomain
Create your node server app at /var/www/yourdomain/app.js
and run it at localhost:3000
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(3000, "127.0.0.1");
console.log('Server running at http://127.0.0.1:3000/');
Restart Nginx:
sudo /etc/init.d/nginx restart
Lastly start the node server:
cd /var/www/yourdomain/ && node app.js
Now you should see "Hello World" at yourdomain.com
References & Resources
- N/A
Latest Post
- Dependency injection
- Directives and Pipes
- Data binding
- HTTP Get vs. Post
- Node.js is everywhere
- MongoDB root user
- Combine JavaScript and CSS
- Inline Small JavaScript and CSS
- Minify JavaScript and CSS
- Defer Parsing of JavaScript
- Prefer Async Script Loading
- Components, Bootstrap and DOM
- What is HEAD in git?
- Show the changes in Git.
- What is AngularJS 2?
- Confidence Interval for a Population Mean
- Accuracy vs. Precision
- Sampling Distribution
- Working with the Normal Distribution
- Standardized score - Z score
- Percentile
- Evaluating the Normal Distribution
- What is Nodejs? Advantages and disadvantage?
- How do I debug Nodejs applications?
- Sync directory search using fs.readdirSync