Running multiple Node (Express) apps on same port

Javascriptnode.jsExpress

Javascript Problem Overview


I have multiple Node applications (build on Express framework).

Now I have placed them like this -

  • /var/www/app1
  • /var/www/app2
  • /var/www/app3

Now I want to run these 3 apps on the same port (say 8080). Is that possible ?

One thing to note is that, Each app has common routes like these -

  • app.get('/', func...);
  • app.get('/about', func...);
  • app.post('/foo', func...);
  • app.post('/bar', func...);

Basically I want to do it like you can do with Apache/PHP setup.

So with a LAMP stack when you have -

  • /var/www/app1
  • /var/www/app2
  • /var/www/app3

You can easily access them as different apps from -

  • localhost/app1
  • localhost/app2
  • localhost/app3

Javascript Solutions


Solution 1 - Javascript

You can use app.use():

app
  .use('/app1', require('./app1/index').app)
  .use('/app2', require('./app2/index').app)
  .listen(8080);

Solution 2 - Javascript

You could run them as seperate apps listening to different ports and then have a proxy (like https://github.com/nodejitsu/node-http-proxy/ ) serving everything on 8080 depending on the requested URL.

like:

var options = {
  router: {
    'foo.com/baz': '127.0.0.1:8001',
    'foo.com/buz': '127.0.0.1:8002',
    'bar.com/buz': '127.0.0.1:8003'
  }
};

Works like charm for me ( http://nerdpress.org/2012/04/20/hosting-multiple-express-node-js-apps-on-port-80/). I wasn't so keen on having them mounted as sub-apps, as suggested in the comments because i wanted them to run independently...

Solution 3 - Javascript

You can create one main app(say app) parallel to you apps, and have it initializing the secondary apps (in your case app1, app2, app3) using

app.use('<the_context_you_need>', require('./app1/yourApp.js')

All your apps (app1, app2, app3) need to create app and export it by using

var app = module.exports = express();

You need not create instance of server or call app.listen in all the subapps; all the sub-apps can be served via main app listen port.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1437328View Question on Stackoverflow
Solution 1 - Javascriptuser1437328View Answer on Stackoverflow
Solution 2 - JavascriptmgherkinsView Answer on Stackoverflow
Solution 3 - JavascriptKamesh ChauhanView Answer on Stackoverflow