nestjs 마이크로서비스 초기 구성중 실행 문제

728x90
nest new nestjs-msa
cd nestjs-msa
nest g app user-service
nest g app api-gateway

 

각 서비스는 apps/ 폴더 밑에 생성됨

 

user-service/main.ts 수정

import { NestFactory } from '@nestjs/core';
import { MicroserviceOptions, Transport } from '@nestjs/microservices';
import { UserServiceModule } from './user-service.module';

async function bootstrap() {
  const app = await NestFactory.createMicroservice<MicroserviceOptions>(
    UserServiceModule,
    {
      transport: Transport.TCP,
      options: { host: '127.0.0.1', port: 3001 },
    },
  );
  await app.listen();
}
bootstrap();

 

api-gateway/module.ts 수정

import { Module } from '@nestjs/common';
import { ApiGatewayController } from './api-gateway.controller';
import { ApiGatewayService } from './api-gateway.service';
import { ClientsModule, Transport } from '@nestjs/microservices';

@Module({
  imports: [
    ClientsModule.register([
      {
        name: 'USER_SERVICE',
        transport: Transport.TCP,
        options: {
          host: '127.0.0.1',
          port: 3001,
        },
      },
    ]),
  ],
  controllers: [ApiGatewayController],
  providers: [ApiGatewayService],
})
export class ApiGatewayModule {}

 

 

cd apps/user-service
npm run start:dev

cd apps/api-gateway
npm run start:dev

 

실행해보면 먼저 실행한 user-service는 정상적이고 api-gateway는 3000포트 사용 이슈로 실행이 안될 것이다.

 

이유는 모노레포 구조로 구성을 했기 때문에 package.json이 루트에 하나만 존재하기 때문에 루트에 package.json을 보면

"start:dev": "nest start --watch",

 

기본적인 실행이기 때문에 루트에 nestjs 프로젝트가 실행된다.

 

package.json에

"start:api-gateway": "nest start api-gateway --watch",
    "start:user-service": "nest start user-service --watch",

를 추가하여

 

npm run start:api-gateway
npm run start:user-service

 

실행 후 테스트 해보면 정상적으로 api-gateway로 요청 응답을 확인해볼 수 있다.

반응형