project/NestJS + Kubernetes & 마이크로서비스 배포

📌 NestJS + Kubernetes & 마이크로서비스 배포: 실전 가이드 - NestJS GraphQL Federation 기반 API Gateway 구축

octo54 2025. 4. 14. 10:42
반응형

📌 NestJS + Kubernetes & 마이크로서비스 배포: 실전 가이드

12. NestJS GraphQL Federation 기반 API Gateway 구축


마이크로서비스 환경에서 GraphQL을 각 서비스에 분산 적용하려면, 이를 하나의 통합 API로 제공하는 Federation 구조가 필요합니다.
NestJS는 Apollo Federation을 완벽히 지원하며, GraphQL Gateway + 각 마이크로서비스가 GraphQL Subgraph를 구성하는 방식으로 확장성과 유지보수성을 높일 수 있습니다.
이번 글에서는 NestJS 기반의 GraphQL Federation 시스템을 설계하고 Kubernetes 환경에 배포하는 실전 전략을 다룹니다. 🚀


✅ 1. GraphQL Federation이란?

GraphQL Federation은 여러 GraphQL 서비스(Subgraphs)를 하나의 통합된 스키마로 병합해주는 분산 GraphQL 아키텍처입니다.

구성 요소 설명

Gateway 클라이언트의 요청을 받아 서브그래프로 분산
Subgraph 각 마이크로서비스에 존재하는 GraphQL 서버
Apollo Router Apollo Studio 연동 및 고성능 GraphQL Gateway 가능

✅ 2. NestJS Federation 환경 구성

npx create-nx-workspace nest-federation
cd nest-federation
npm install @nestjs/graphql @apollo/subgraph graphql @apollo/federation

✅ 3. User Subgraph 예제

반응형

📂 apps/user-service/src/user.module.ts

@Module({
  imports: [
    GraphQLModule.forRoot({
      autoSchemaFile: true,
      driver: ApolloFederationDriver,
    }),
  ],
  providers: [UserResolver],
})
export class UserModule {}

📂 user.resolver.ts

@ObjectType()
@Directive('@key(fields: "id")')
export class User {
  @Field(() => ID)
  id: string;

  @Field()
  name: string;
}

@Resolver(() => User)
export class UserResolver {
  @Query(() => [User])
  users() {
    return [{ id: '1', name: 'Alice' }];
  }

  @ResolveReference()
  resolveReference(reference: { __typename: string; id: string }) {
    return { id: reference.id, name: 'Ref Alice' };
  }
}

✅ 4. API Gateway 설정 (Apollo Gateway)

npm install @apollo/gateway @nestjs/apollo

📂 apps/api-gateway/main.ts

const gateway = new ApolloGateway({
  serviceList: [
    { name: 'user', url: 'http://localhost:3001/graphql' },
    { name: 'order', url: 'http://localhost:3002/graphql' },
  ],
});

const server = new ApolloServer({
  gateway,
  subscriptions: false,
  introspection: true,
});

💡 Federation Gateway는 실제로 GraphQL 스키마를 병합하고, 각 요청을 해당 마이크로서비스로 자동 라우팅합니다.


✅ 5. Federation과 Kubernetes 연동

각 서비스는 Kubernetes 내에서 도메인으로 라우팅됩니다:

serviceList:
  - name: user
    url: http://user-service.default.svc.cluster.local/graphql
  - name: order
    url: http://order-service.default.svc.cluster.local/graphql

Ingress 또는 API Gateway에서도 GraphQL 요청은 한곳으로 받고 내부적으로 서브그래프들로 요청 분기


✅ 6. Federation 운영 전략

항목 전략

버전 관리 각 Subgraph는 독립적으로 배포 가능
스키마 병합 @key, @extends, @external을 통해 조합
Auth 적용 Gateway에서 JWT 검증 후 context 전달
Subgraph 동적 등록 Apollo Studio / Router 연동
중단 없는 배포 Subgraph 스키마 변경 시 backwards compatibility 유지

✅ 7. Apollo Router (대안)

Apollo Gateway보다 성능, 보안, 배포 유연성이 높은 Rust 기반 Gateway

  • 설치는 Docker 또는 Binary
  • Subgraph 자동 등록 및 캐시 관리
  • NestJS와 연동 시 Gateway 대신 프록시 역할

✅ 결론: NestJS로 GraphQL Federation 아키텍처 완성

✅ 각 마이크로서비스가 독립된 GraphQL API (Subgraph) 제공
✅ Apollo Federation으로 하나의 API로 병합
✅ API Gateway는 인증, 트래픽 분산, 서브그래프 관리 담당
✅ Kubernetes 환경에서 서브그래프 간 통신 구조 간단하게 구성

다음 글에서는 NestJS 기반 프로젝트를 SaaS 모델로 전환하기 위한 사용자, 과금, 역할 기반 인증 설계를 다룹니다! 💳


🔍 다음 글 예고: NestJS SaaS 모델 전환 – 사용자/권한/결제 시스템 설계

📌 다음 편: 13. NestJS SaaS 시스템 설계: 인증, 요금제, 다중 테넌시


 

NestJS GraphQL,NestJS Federation,NestJS GraphQL Gateway,NestJS Apollo Federation,NestJS Subgraph,NestJS GraphQL 마이크로서비스,Apollo Router,NestJS GraphQL Kubernetes,NestJS 실시간 API,NestJS GraphQL 통합