0Pricing
NestJS Enterprise Backend APIs · 강의

Prometheus를 활용한 모니터링

Prometheus를 연동하여 지표를 수집하고 대시보드를 구축함으로써 NestJS 애플리케이션의 성능과 상태를 모니터링합니다.

Prometheus를 활용한 모니터링은(는) CoddyKit의 무료 NestJS Enterprise Backend APIs 강의입니다. 이것은 3개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 NestJS Enterprise Backend APIs 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. NestJS Enterprise Backend APIs 강의에는 총 3개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Why Monitor Your App?

Monitoring is crucial for understanding your application's health and performance. It helps you catch issues early, debug problems, and ensure a smooth user experience.

  • Performance: Is your API fast enough?
  • Availability: Is your service online and responding?
  • Errors: Are there unexpected failures?
  • Resource Usage: How much CPU, memory, or disk space is being used?

Without monitoring, you're flying blind!

Meet Prometheus

Prometheus is an open-source monitoring system designed for reliability and scalability. It collects metrics from your applications and infrastructure, storing them as time-series data.

Think of it as a vigilant observer, constantly gathering data points about your system's behavior over time.

Prometheus Architecture

Prometheus works by scraping (pulling) metrics from configured targets. Key components:

  • Prometheus Server: The core component that scrapes, stores, and queries metrics.
  • Exporters: Specialized agents that expose existing metrics from third-party systems (like databases, OS) in a Prometheus-compatible format.
  • Client Libraries: Integrate directly into application code to expose custom metrics (what we'll use in NestJS).
  • Grafana: A popular dashboard tool for visualizing Prometheus data.

NestJS & `nestjs-prometheus`

To integrate Prometheus with a NestJS application, we use the nestjs-prometheus library. It simplifies exposing metrics and creating custom ones.

This library acts as a bridge, allowing your NestJS app to generate and expose metrics that the Prometheus server can then scrape.

Setting Up `nestjs-prometheus`

First, install the package:

npm install --save @willsoto/nestjs-prometheus prom-client

Then, import PrometheusModule into your root module (e.g., AppModule) and configure it:

import { Module } from '@nestjs/common';
import { PrometheusModule } from '@willsoto/nestjs-prometheus';
import { AppController } from './app.controller';

@Module({
  imports: [
    PrometheusModule.register({
      path: '/metrics',
      collectDefaultMetrics: true
    })
  ],
  controllers: [AppController],
  providers: [],
})
export class AppModule {}

Exposing Default HTTP Metrics

With collectDefaultMetrics: true, nestjs-prometheus automatically exposes basic Node.js process metrics. To also expose HTTP request metrics, you need to add an interceptor.

Update your main.ts to enable this:

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { PrometheusInterceptor } from '@willsoto/nestjs-prometheus';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalInterceptors(new PrometheusInterceptor());
  await app.listen(3000);
  console.log('App is running on port 3000');
  // Access metrics at http://localhost:3000/metrics
}
bootstrap();

Custom Metrics: Counter

A Counter is a cumulative metric that represents a single monotonically increasing value. It can only go up or be reset to zero on restart. Use it for things like the total number of requests served, errors encountered, or items processed.

Here's how to inject and use a custom counter in a service:

import { Injectable } from '@nestjs/common';
import { InjectMetric } from '@willsoto/nestjs-prometheus';
import { Counter } from 'prom-client';

@Injectable()
export class UserService {
  constructor(
    @InjectMetric('users_created_total') public usersCreatedCounter: Counter,
  ) {}

  createUser(name: string): string {
    // Logic to create a user...
    this.usersCreatedCounter.inc(); // Increment the counter
    return `User ${name} created`;
  }
}

Custom Metrics: Gauge

A Gauge is a metric that represents a single numerical value that can arbitrarily go up and down. Use it for things like current memory usage, number of concurrent requests, or the current queue size.

Let's track active connections with a Gauge:

import { Injectable } from '@nestjs/common';
import { InjectMetric } from '@willsoto/nestjs-prometheus';
import { Gauge } from 'prom-client';

@Injectable()
export class ConnectionService {
  constructor(
    @InjectMetric('active_connections_count') public activeConnectionsGauge: Gauge,
  ) {}

  connectUser(): void {
    // User connects logic...
    this.activeConnectionsGauge.inc(); // Increment active connections
  }

  disconnectUser(): void {
    // User disconnects logic...
    this.activeConnectionsGauge.dec(); // Decrement active connections
  }
}

Other Metric Types

Prometheus also offers other metric types for more specific use cases:

  • Histogram: Samples observations (e.g., request durations) and counts them in configurable buckets. Useful for understanding distributions and percentiles.
  • Summary: Similar to Histogram but calculates configurable quantiles over a sliding time window. Good for latency.

For most common scenarios, Counters and Gauges are often sufficient.

Visualizing with Grafana

While Prometheus collects metrics, Grafana is typically used to visualize them. Grafana connects to Prometheus as a data source and allows you to build powerful, customizable dashboards.

You can create graphs, charts, and alerts based on the metrics exposed by your NestJS application, giving you real-time insights into its performance and health.

Quick Check

You've learned about setting up Prometheus monitoring in NestJS.

Recap: Monitoring with Prometheus

In this lesson, you learned the importance of monitoring and how Prometheus helps collect time-series metrics from your NestJS application.

  • We explored the Prometheus architecture and its components.
  • You saw how to integrate nestjs-prometheus to expose default and custom metrics.
  • We distinguished between Counter and Gauge metric types.
  • Finally, we touched on how Grafana is used for powerful visualization.

Monitoring is a vital practice for maintaining robust and performant applications!

자주 묻는 질문

“Prometheus를 활용한 모니터링” 강의는 무료인가요?

네 — “Prometheus를 활용한 모니터링” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 NestJS Enterprise Backend APIs 강의 전체를 잠금 해제할 수 있습니다. NestJS Enterprise Backend APIs 강의에는 총 3개의 강의가 포함되어 있습니다.

“Prometheus를 활용한 모니터링”에서 뭘 배우나요?

Prometheus를 연동하여 지표를 수집하고 대시보드를 구축함으로써 NestJS 애플리케이션의 성능과 상태를 모니터링합니다. 브라우저에서 직접 실행하는 실습 코드로 NestJS Enterprise Backend APIs을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

NestJS Enterprise Backend APIs을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 NestJS Enterprise Backend APIs은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 3개 중 3번째 강의입니다.

“Prometheus를 활용한 모니터링” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 NestJS Enterprise Backend APIs 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 NestJS Enterprise Backend APIs 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 요청률 제한과 조절
  2. Winston/Pino를 활용한 로깅
  3. Prometheus를 활용한 모니터링
← NestJS Enterprise Backend APIs(으)로 돌아가기