Scalable Node.js With Nginx
First be sure you have installed Nginx and Node.js.
The next thing you should do is to edit Nginx configuration file.
The config file location is mostly like under /etc/Nginx/nginx.conf.
Open the config file via vim or nano and make those changes.
http {
upstream node_app {
server 127.0.0.1:8080;
server 127.0.0.1:8081;
}
server {
listen 80;
server_name domain1.com;
location ~* ^.+\.(jpg|jpeg|png|ico|css|txt|js|html|htm)$ {
root /var/www/html/domain1.com/public/;
}
location ~* ^[^\.]+$ {
proxy_redirect off;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
proxy_set_header Connection "";
proxy_http_version 1.1;
proxy_pass http://node_app;
}
}
}
In the first part we add our node applications to http handler. In this example we have two nodes running.
upstream node_app {
server 127.0.0.1:8080;
server 127.0.0.1:8081;
}
To serve static files using nginx we add those locations to our http handler. In this example we just used jpg, jpeg, js and css extentions.
location ~* ^.+\.(jpg|jpeg|css|js)$ {
root /var/www/html/domain1.com/public/;
}
For dynamic content we set a proxy on nginx. So if we handle a dynamic content request, we are passing those request to one of nodes defined. In this example just looking for locations which doesn't contain any . (dot) character. You can simply set your location rules by using Regular Expressions.
location ~* ^[^\.]+$ {
proxy_redirect off;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
proxy_set_header Connection "";
proxy_http_version 1.1;
proxy_pass http://node_app;
}
Hope that helps.
Thanks.