如何在启动过程中动态配置应用选项(如端口、中间件、全局前缀)?

解读

国内面试官问“动态配置”时,往往不只是想知道“能改端口”,而是想确认候选人是否:

  1. 能把配置与代码彻底解耦,满足多环境(dev/test/stage/prod)一键部署;
  2. 能在容器化、K8s、Serverless 场景下通过环境变量或配置中心(Apollo、Nacos、Consul)实时注入;
  3. 能在应用生命周期的最早阶段(Factory 阶段)就拿到最终值,避免“先启动后改端口”这类二次重启;
  4. 能把端口、中间件、全局前缀等“运行时选项”一起纳入同一套配置模型,保持可测、可灰度、可回滚。

如果回答只停留在 const port = process.env.PORT || 3000,会被视为“初级水平”。

知识点

  1. 配置源优先级:命令行参数 > 环境变量 > .env.{环境} 文件 > 默认值;国内运维普遍要求“12-Factor App”。
  2. NestJS 配置工厂:ConfigModule.forRoot({ load: [() => config], validationSchema, validationOptions }),在 IoC 容器初始化前完成同步校验。
  3. 动态模块与异步工厂:ConfigModule.forRoot({ isGlobal: true, envFilePath: getEnvFile(), load: [databaseConfig, serverConfig] }),支持异步读取配置中心。
  4. 应用级工厂:NestFactory.createApplicationContext(AppModule) 或 NestFactory.create(AppModule) 之前,用 NestApplicationContext 先拿到 ConfigService,再决定 app.listen(port)。
  5. 中间件动态挂载:MiddlewareConsumer 只能在模块编译期决定顺序;真正的“动态”要在 bootstrap 里用 app.use() 根据配置开关一次性挂载,且必须在 app.init() 之前完成。
  6. 全局前缀与多租户:通过 app.setGlobalPrefix(config.get('apiPrefix'), { exclude: config.get('excludeGlobalPrefixRoutes') }) 支持版本号或租户标识,如 /api/v1/:tenant。
  7. 配置热重载:国内金融、政务项目要求“不停机变更”,可结合 node-config + chokidar 监听配置中心推送,收到变更后触发 app.close() 再 bootstrap(),或利用 PM2/cluster 滚动重启。
  8. 类型安全:用 interface ServerConfig { port: number; apiPrefix: string; corsOrigins: string[] } 并配合 class-validator 在启动前做一次 validateSync,失败直接 process.exit(1),防止带病上线。

答案

下面给出一条可直接落地的“国内云原生”最佳实践,覆盖端口、中间件、全局前缀的“真正动态”配置。

  1. 定义配置对象(src/config/server.config.ts)
import { registerAs } from '@nestjs/config';
import { IsInt, Min, Max, IsString, IsOptional } from 'class-validator';
import { validateSync } from 'class-validator';

class ServerConfigDto {
  @IsInt() @Min(1024) @Max(65535)
  PORT: number;

  @IsString()
  API_PREFIX: string;

  @IsOptional() @IsString()
  CORS_ORIGINS?: string;
}

export default registerAs('server', () => {
  const dto = Object.assign(new ServerConfigDto(), {
    PORT: Number(process.env.PORT) || 3000,
    API_PREFIX: process.env.API_PREFIX || '/api',
    CORS_ORIGINS: process.env.CORS_ORIGINS,
  });
  const errors = validateSync(dto, { forbidUnknownValues: true });
  if (errors.length) throw new Error(`ServerConfig invalid: ${errors}`);
  return dto;
});
  1. 在 AppModule 中异步加载(支持配置中心)
@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      load: [serverConfig],
      // 若用 Apollo/Nacos,可在此写自定义 ConfigService 工厂
    }),
  ],
})
export class AppModule {}
  1. bootstrap 函数(main.ts)——在 listen 之前就拿到最终配置
async function bootstrap() {
  // 1. 先创建应用上下文,不监听端口
  const app = await NestFactory.create(AppModule, { bufferLogs: true });
  const config = app.get(ConfigService);

  // 2. 一次性读取所有运行时选项
  const port = config.get<number>('server.PORT');
  const apiPrefix = config.get<string>('server.API_PREFIX');
  const corsOrigins = config.get<string>('server.CORS_ORIGINS')?.split(',') || [];

  // 3. 动态设置全局前缀
  app.setGlobalPrefix(apiPrefix, {
    exclude: [{ path: 'health', method: RequestMethod.GET }],
  });

  // 4. 根据配置开关动态挂载中间件
  if (config.get('server.USE_REQUEST_ID') !== 'false') {
    app.use(addRequestId()); // 自定义中间件
  }
  app.use(helmet({ contentSecurityPolicy: false }));
  app.enableCors({ origin: corsOrigins, credentials: true });

  // 5. 统一异常过滤器、日志格式等
  app.useGlobalFilters(new AllExceptionsFilter());
  app.useLogger(app.get(MyLogger));

  // 6. 初始化 IoC 容器,再监听端口
  await app.init();
  await app.listen(port);
  Logger.log(`🚀 服务已启动:http://0.0.0.0:${port}${apiPrefix}`, 'Bootstrap');
}
bootstrap().catch((e) => {
  Logger.error('启动失败', e);
  process.exit(1);
});
  1. 多环境启动脚本(package.json)
"start:dev": "cross-env NODE_ENV=development API_PREFIX=/api/dev nest start --watch",
"start:prod": "node dist/main",

在 Dockerfile 里只写 CMD ["node", "dist/main"],所有差异通过 K8s ConfigMap/Secret 注入环境变量,实现“同一镜像,多环境运行”。

拓展思考

  1. 配置中心灰度:当配置中心(如 Apollo)推送“端口=3001”时,直接改 process.env.PORT 无法生效,因为 listen() 已经执行。生产级方案是:
    • 利用 cluster 模式,主进程监听配置变更,滚动重启 worker;
    • 或者把 NestJS 封装成 npm run start:cluster,通过 PM2 pm2 reload ecosystem.config.js --update-env 实现零宕机。
  2. Serverless 场景:函数计算(阿里云 FC、腾讯云 SCF)没有“端口”概念,但仍有“全局前缀”需求(如自定义域名映射)。此时把 apiPrefix 抽到 serverless.yml 的 environment 里,在 bootstrap 里判断 process.env.FC_FUNC_PREFIX,动态 setGlobalPrefix,保证本地开发、容器、Serverless 三端代码同一套。
  3. 配置版本与回滚:金融项目要求“配置可审计”,可把每次启动的 serverConfig 序列化成 JSON,写入日志并上报到 ELK,同时把配置 MD5 作为标签打到镜像元数据里,出现线上问题时能按“配置版本”快速回滚镜像或配置。
  4. 动态中间件顺序:NestJS 的 MiddlewareConsumer 只能在编译期决定顺序。若业务要求“根据租户开关限流中间件”,可在 app.use() 阶段用高阶函数包裹,实现条件执行,但注意这会跳过 NestJS 的依赖注入体系,需要手动从 app.get() 取出服务实例。