当前位置: 动力学知识库 > 问答 > 编程问答 >

heroku: route subdirectory to a second node.js app?

问题描述:

I have a heroku node.js app running under the domain foo.com. I want to proxy all urls beginning with foo.com/bar/ to a second node.js process - but I want the process to be controlled within the same heroku app. Is this possible?

If not, is it possible to proxy a subdirectory to a second heroku app? I haven't been able to find much control over how to do routing outside of the web app's entry point. That is, I can easily control routing within node.js using Express for example, but that doesn't let me proxy to a different app.

My last resort is simply using a subdomain instead of a subdirectory, but I'd like to see if a subdirectory is possible first. Thanks!

Edit: I had to solve my problem using http-proxy. I have two express servers listening on different ports and then a third externally facing server that routes to either of the two depending on the url. Not ideal of course, but I couldn't get anything else to work. The wrap-app2 approach described below had some url issues that I couldn't figure out.

网友答案:

Just create a new express server and put a middleware in the main one to redirect to the secondary when comes a request to your desired path:

  var app2 = express();

  app2.use(function(req, res){
      res.send('Hey, I\'m another express server');
  });

  app.use('/foo', app2);

I haven't tried it yet in Heroku, but it the same process and doesn't create any new TCP binding or process, so It will work. For reference, a modified plain express template.

And if you really want other express process handling the connection, you need to use cluster. Check the worker.send utility.

  app.use('/foo', function(req,res){
        //You can send req too if you want.
        worker.send('foo', res);
  });
网友答案:

This is possible. The most elegant way I could think is by using clustering. 1 Heroku Dyno contains four cores. Therefore, you can run four worker threads to a node process.

Here is an introduction to clustering.

What you're looking at is initializing two express apps (assuming you're using express) and serving those two in two worker threads.

if (cluster.isMaster) {
    //  let's make four child processes
    for (var i = 0; i < 4; i++) {
        if (i%2 == 0) {
           cluster.fork(envForApp1);
        } else {
           cluster.fork(envForApp2);
        }
    }
} else {
    // refer to NODE_ENV and see whether this should be your app1 or app2
    // which should be started. This is passed from the fork() before.

    app.listen(8080);
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: