Running multiple nodejs app in ONE server using Nginx
Environment
This is running on Ubuntu 13.10
Here I would like to use Sails.js framework (version 0.9.13) to create node.js app.
1. Install node.js on Ubuntu
1 | $ sudo apt-get install python-software-properties python g++ make |
2. Create 2 apps
Install Sails.js globally
1 | $ sudo npm -g install sails |
Create projects
1 | cd |
Edit the home page for both projects (to differentiate them)
project1/views/home/index.ejs
1 | <h1>This is project 1</h1> |
project2/views/home/index.ejs
1 | <h1>This is second project</h1> |
3. Change the environment to production
project1/config/local.js
1 | module.exports = { |
project2/config/local.js
1 | module.exports = { |
In order to make the app run on background, we need forever
1 | $ sudo npm install -g forever |
Now start the app using forever
1 | $ cd ~/public_html/project1 |
Let’s open up your browser, and type localhost:8081
… Oops… it doesn’t work like expected
Let’s check the log
1 | $ forever logs |
See the content of the file
1 |
|
Now, the error tell us that we need to install Sails.js locally
1 | forever stopall # stop all process |
Repeat the same thing on project2
Now open up the browser, it should show up the content.
4. Bind different domain name to different project
First, we need Nginx
1 | $ sudo apt-get install nginx |
Configure Nginx to listen to port 80 and forword the request to different app based by the port number
1 | cd /etc/nginx/sites-available/ |
Put the content to sails1.com.conf
1 | server { |
This tell the server that forword the request from sails1.com to http://localhost:8081 (which is the project1)
Just do the same thing for project2
1 | server { |
Enable the config. (In order to make the config file take effect, symlink them to sites-enabled directory)
1 | $ sudo ln -s /etc/nginx/sites-available/sails1.com.conf /etc/nginx/sites-enabled/sails1.com.conf |
Restart Nginx server
1 | $ sudo service nginx restart |
Since I’m testing on local machine, so we need to edit the hosts file, append the content below the hosts file
/etc/hosts
1 | # nginx virtual host |
5. Done
Basically what we do here is Reverse proxy, Nginx listen to the port 80 and passing the request to different app.
References: