简体   繁体   English

在同一端口上运行多个 Node (Express) 应用程序

[英]Running multiple Node (Express) apps on same port

I have multiple Node applications (build on Express framework).我有多个 Node 应用程序(构建在 Express 框架上)。

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).现在我想在同一个端口(比如 8080)上运行这 3 个应用程序。 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.基本上我想像使用 Apache/PHP 设置那样做。

So with a LAMP stack when you have -所以当你有一个 LAMP 堆栈时 -

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

You can easily access them as different apps from -您可以轻松访问它们作为不同的应用程序 -

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

You can use app.use() :您可以使用app.use()

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

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.您可以将它们作为单独的应用程序运行,侦听不同的端口,然后使用代理(如https://github.com/nodejitsu/node-http-proxy/ )根据请求的 URL 为 8080 上的所有内容提供服务。

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/ ).对我来说就像魅力一样( 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...我不太热衷于将它们安装为子应用程序,正如评论中所建议的那样,因为我希望它们独立运行......

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您可以创建一个与您的应用程序并行的主应用程序(比如应用程序),并使用它初始化辅助应用程序(在您的情况下为 app1、app2、app3)

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您所有的应用程序(app1、app2、app3)都需要创建应用程序并使用

var app = module.exports = express();

You need not create instance of server or call app.listen in all the subapps;您无需在所有子应用程序中创建服务器实例或调用 app.listen; all the sub-apps can be served via main app listen port.所有子应用程序都可以通过主应用程序监听端口提供服务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM