使用 Nestjs 提供公共和私有端口服务

Eri*_*maa 5 express nestjs

我正在构建一个旨在为移动应用程序提供服务的应用程序。除了为客户提供服务外,它还将具有多种后台功能。

我们正在使用swagger,并且我们确实希望能够访问后台端点的 swagger 文档。但是,我们不想公开暴露我们的所有端点。

假设将所有端点公开是一个糟糕的选择,我们正在考虑的一种解决方案是让我们的服务器服务两个端口,然后只向公众公开一个端口。我们创建了一个小型示例存储库,为两个不同端口上的客户端模块和后台模块提供服务。

看起来main.ts像下面这样:

import { NestFactory } from '@nestjs/core';
import { ClientModule } from './modules/client/client.module';
import * as express from 'express';
import * as http from 'http';
import {ExpressAdapter} from '@nestjs/platform-express';
import { BackOfficeModule } from './modules/backoffice/backoffice.module';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';

async function bootstrap() {

  const clientServer = express();
  const clientApp = await NestFactory.create(
    ClientModule,
    new ExpressAdapter(clientServer),
  );
  const clientOptions = new DocumentBuilder()
    .setTitle('ClientServer')
    .setDescription('The client server API description')
    .setVersion('1.0')
    .addTag('client')
    .build();
  const clientDocument = SwaggerModule.createDocument(clientApp, clientOptions);
  SwaggerModule.setup('api', clientApp, clientDocument);
  await clientApp.init();

  const backOfficeServer = express();
  const backOfficeApp = await NestFactory.create(
    BackOfficeModule,
    new ExpressAdapter(backOfficeServer),
  );

  const backOfficeOptions = new DocumentBuilder()
    .setTitle('BackOffice')
    .setDescription('The back office API description')
    .setVersion('1.0')
    .addTag('backOffice')
    .build();
  const backOfficeDocument = SwaggerModule.createDocument(backOfficeApp, backOfficeOptions);
  SwaggerModule.setup('api', backOfficeApp, backOfficeDocument);
  await backOfficeApp.init();

  http.createServer(clientServer).listen(3000); // The public port (Load balancer will route traffic to this port)
  http.createServer(backOfficeServer).listen(4000); // The private port (Will be accessed through a bastian host or similar)
}
bootstrap();

Run Code Online (Sandbox Code Playgroud)

另一种选择是对代码库和基础设施进行更大的分离,但由于这是一个非常早期的阶段,我们认为这是不必要的。

因此,我们向Nest社区提出的问题是,有人这样做过吗?如果是这样,您的经验是什么?像这样分离后端代码有什么缺点?

iam*_*gga 1

没关系,但是如果您想在一台主机上运行两台服务器,我建议创建两个文件,例如main-client.ts和 ,main-back-office.ts并在不同的进程中运行它们,因为在这种情况下,一台服务器的故障不会影响另一台服务器的工作。

另外,如果你没有运行这个,Docker我会建议使用像foreverpm2supervisor或我自己的非常小的图书馆workers-cluster这样的工具

如果您运行它Docker并且不想进行大重构,我建议Dockerfile通过运行不同的CMDENTRYPOINT命令来创建单个