---
title: "PrometheusとGrafanaを使ったマイクロサービスの監視 - API7.ai"
description: "This tutorial walks you through setting up monitoring on a microservice application using Prometheus and Grafana."
url: "https://navendu.me/posts/introduction-to-monitoring-microservices/"
---

[Blog](https://api7.ai/ja/blog)

[Products](https://api7.ai/ja/category/products)[Technology](https://api7.ai/ja/category/technology)[Ecosystem](https://api7.ai/ja/category/ecosystem)[Case Study](https://api7.ai/ja/category/usercase)[Team & Community](https://api7.ai/ja/category/community)

Search

⌘ + K

[Blog](https://api7.ai/blog)

Ecosystem

# PrometheusとGrafanaを使ったマイクロサービスの監視

[![Navendu Pottekkat](https://avatars.githubusercontent.com/u/49474499?v=4)](https://github.com/pottekkat)

[Navendu Pottekkat](https://github.com/pottekkat)

June 8, 2023

[Ecosystem](https://api7.ai/category/ecosystem)

マイクロサービスシステムを堅牢にするためには、継続的な監視が不可欠です。適切な監視がないと、マイクロサービスはすぐに過負荷になり、エラーやパフォーマンスの低下を引き起こす可能性があります。

継続的な監視を通じて、開発者はサービスに問題が発生した際にすぐに検出し、重大な損害を防ぐための対策を講じることができます。また、サービスのパフォーマンスに関する洞察を提供し、情報に基づいた意思決定を可能にします。

この記事では、[Prometheus](https://prometheus.io/) と [Grafana](https://grafana.com/) という2つの人気ツールを使用して、マイクロサービスアプリケーションに監視を設定する方法を紹介します。

このチュートリアルのソースコードとDocker Composeファイルは、[pottekkat/monitoring-101](https://github.com/pottekkat/monitoring-101) で入手できます。

## Prometheusの基本

Prometheusは、オープンソースの監視およびアラートツールです。マイクロサービスからHTTPリクエストを送信してメトリクス（測定値）を「プル」し、その結果を時系列データベースに保存します。

Prometheusが提供する[クライアントライブラリ](https://prometheus.io/docs/instrumenting/clientlibs/)を使用して、サービスを計装することができます。これにより、サービスからカスタムメトリクスを作成して収集することが可能になります。

Prometheusには、Prometheus形式ではないメトリクスをプルするための[エクスポーター](https://prometheus.io/docs/instrumenting/exporters/)もあります。エクスポーターは仲介役として機能し、エクスポートされたデータをPrometheusが読み取れる形式に変換します。

![1-prometheus-architecture.png](https://static.api7.ai/2022/12/02/6389c0285500d.png?imageMogr2/format/webp)

Prometheusは、収集したデータを操作するための強力なクエリ言語である[PromQL](https://prometheus.io/docs/prometheus/latest/querying/basics/)を提供しています。PromQLを使用して、データをフィルタリング、集計、変換するための複雑なクエリを作成できます。

メトリクスをプルするだけでなく、Prometheusは設定された閾値を超えた場合に[アラート](https://prometheus.io/docs/alerting/latest/overview/)をトリガーすることもできます。アラートメカニズムは高度に設定可能で、Slackやメールなどに通知を送信できます。

Prometheusには、収集したメトリクスを簡単に視覚化するためのGUIも備わっています。また、Grafanaのような高度な視覚化ツールとも統合できます。

![prometheus-dashboard.png](https://static.api7.ai/2022/12/02/6389c09a1df30.png?imageMogr2/format/webp)

### メトリクスの種類

Prometheusは、4つの主要なメトリクスタイプを提供しています：

1. **Counter**: 単調増加するカウンターを表します。値は増加するか、再起動時にゼロにリセットされます。リクエスト数などのメトリクスを表すために使用できます。
2. **Gauge**: 上下する数値を表します。メモリ使用量や1秒あたりのリクエスト数などの値を表すために使用できます。
3. **Histogram**: データを設定可能なバケットにサンプリングします。リクエストの持続時間やレスポンスサイズなどの値を表すために使用できます。
4. **Summary**: Histogramと同様に、スライディングタイムウィンドウで設定可能な値を計算します。

これらのメトリクスタイプとその使用方法について詳しくは、[公式ドキュメント](https://prometheus.io/docs/tutorials/understanding_metric_types/)を参照してください。

## サンプルアプリケーション

この[サンプルアプリケーション](https://github.com/pottekkat/monitoring-101)は、APIゲートウェイ、Goアプリ、Pythonアプリで構成されています。

![2-sample-app-flowchart.png](https://static.api7.ai/2022/12/02/6389c02873b98.png?imageMogr2/format/webp)

このアプリケーションは、選択した言語で「Hello \<name>!」を返します。Apache APISIXがAPIゲートウェイとして機能し、トラフィックをサービスに転送します。

以下の図は、システムの動作を示しています。

![3-sample-app-sequence.png](https://static.api7.ai/2022/12/02/6389c02837835.png?imageMogr2/format/webp)

1. ユーザーがAPISIXにGETリクエストを送信します。APISIXはアプリケーションのエントリーポイントです。
2. APISIXがリクエストをGoサービスに転送します。
3. GoサービスがPythonサービスにGETリクエストを送信し、指定された言語で「Hello」を取得します。
4. Pythonサービスが「Hello」の翻訳を返します。
5. Goサービスがクエリで提供された名前を使用して必要なレスポンスを作成し、APISIXに送信します。
6. APISIXがレスポンスをユーザーに返します。

## Prometheusを設定してメトリクスを収集する

アプリケーション内のすべてのサービスからメトリクスを計装してエクスポートし、Prometheusで収集します。まず、APIゲートウェイである[Apache APISIX](https://api7.ai/apisix)から始めます。

### APISIXからメトリクスをエクスポートする

Apache APISIXは、オープンソースのクラウドネイティブAPIゲートウェイです。

APISIXについて詳しく知る必要はなく、提供されている[Docker Composeファイル](https://github.com/pottekkat/monitoring-101/blob/master/docker-compose.yml)を使用してすべてを設定できます。APISIXについて詳しく知りたい場合は、[api7.ai/apisix](https://api7.ai/apisix)を参照してください。

APISIXは、Prometheus形式でメトリクスを簡単にエクスポートする[prometheusプラグイン](https://docs.api7.ai/apisix/how-to-guide/observability/monitor-apisix-with-prometheus)を提供しています。このプラグインは、APISIXの設定ファイルで設定できます：

```
apisix:
  enable_admin: false # スタンドアロンモードでAPISIXを実行
  config_center: yaml # etcdではなくYAMLファイルを使用して設定を保存
plugin_attr:
  prometheus:
    export_uri: /prometheus/metrics # prometheusプラグインを有効にし、メトリクスをこのURIにエクスポート
    enable_export_server: false # デフォルトのデータプレーンポートでメトリクスをエクスポート
```

次に、すべてのルートでプラグインを有効にするために、[グローバルルール](https://docs.api7.ai/apisix/key-concepts/plugin-global-rules)として設定します：

```
routes:
  # /hello/* へのリクエストをgo-appに転送
  - uri: /hello/*
    upstream:
      type: roundrobin
      nodes:
        "go-app:8080": 1
    plugins:
      # go-appにリクエストを転送する前にプレフィックス "/hello" を削除
      proxy-rewrite:
        regex_uri:
          - "/hello/(.*)"
          - "/$1"
  # 指定されたURIにPrometheusメトリクスをエクスポート
  - uri: /prometheus/metrics
    plugins:
      public-api:
# すべてのルートでPrometheusプラグインをグローバルに有効化
global_rules:
  - id: 1
    plugins:
      prometheus:
        prefer_name: true
#END
```

これにより、Apache APISIXの`/prometheus/metrics`エンドポイントにメトリクスがエクスポートされます。

利用可能なメトリクスについて詳しくは、[ドキュメント](https://apisix.apache.org/docs/apisix/2.15/plugins/prometheus/#available-http-metrics)を参照してください。

### Goサービスからメトリクスを計装してエクスポートする

Prometheusには、Goアプリケーションを計装するための[公式のGoクライアントライブラリ](https://github.com/prometheus/client_golang)があります。

デフォルトでは、PrometheusはデフォルトのGoメトリクスを公開します。また、アプリケーション固有のメトリクスを作成することもできます。

このサービスでは、デフォルトのメトリクスを公開し、リクエスト数を追跡するための独自のカウンターメトリクスを作成します：

```
package main

import (
  "encoding/json"
  "fmt"
  "io/ioutil"
  "log"
  "net/http"
  "os"

  // Prometheusパッケージ
  "github.com/prometheus/client_golang/prometheus"
  "github.com/prometheus/client_golang/prometheus/promauto"
  "github.com/prometheus/client_golang/prometheus/promhttp"
)

// Responseはpython-appから取得したメッセージを格納
type Response struct {
  Message string `json:"message"`
}

// デフォルトの言語と名前
var (
  lang = "en"
  name = "John"
)

// 新しいカスタムPrometheusカウンターメトリクスを作成
var pingCounter = promauto.NewCounter(
  prometheus.CounterOpts{
    Name: "go_app_request_count",
    Help: "go-appが処理したリクエスト数",
  },
)

// HelloHandlerはgo-appへのリクエストを処理
func HelloHandler(w http.ResponseWriter, r *http.Request) {
  lang = r.URL.String()
  name = r.URL.Query()["name"][0]
  
  fmt.Println("Request for", lang, "with name", name)
  pingCounter.Inc()
  
  pUrl := os.Getenv("PYTHON_APP_URL")
  if len(pUrl) == 0 {
    pUrl = "localhost"
  }

  // python-appを呼び出して翻訳を取得
  resp, err := http.Get("http://" + pUrl + ":8000" + lang)
  if err != nil {
    log.Fatalln(err)
  }

  body, err := ioutil.ReadAll(resp.Body)
  if err != nil {
    log.Fatalln(err)
  }

  resp.Body.Close()

  var m Response
  json.Unmarshal(body, &m)

  // 指定された言語で「Hello name!」を返す
  fmt.Fprintf(w, "%s %s!", m.Message, name)
}

func main() {
  // Prometheusメトリクスを公開
  http.Handle("/metrics", promhttp.Handler())
  http.HandleFunc("/", HelloHandler)
  
  http.ListenAndServe(":8080", nil)
}
```

これにより、`/metrics`エンドポイントにメトリクスが公開されます。Goクライアントライブラリについて詳しくは、[GitHubリポジトリ](https://github.com/prometheus/client_golang)を参照してください。

### Pythonサービスからメトリクスを計装してエクスポートする

Prometheusには、[公式のPythonクライアントライブラリ](https://github.com/prometheus/client_python)もあります。特定のユースケースに合わせたサードパーティのライブラリもあります。

このサービスでは、[FastAPI](https://fastapi.tiangolo.com/)を使用しており、[prometheus\_fastapi\_instrumentator](https://github.com/trallnag/prometheus-fastapi-instrumentator#creating-new-metrics)ライブラリを使用して計装します：

```
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from prometheus_fastapi_instrumentator import Instrumentator

app = FastAPI()

hello = {"en": "Hello", "fr": "Bonjour", "es": "Hola", "ml": "ഹലോ"}

# デフォルトのPythonメトリクスを/metricsエンドポイントに公開
Instrumentator().instrument(app).expose(app)

@app.get("/{lang}")
async def get_hello(lang):
    return {"message": hello[lang]}
```

カスタムメトリクスの作成について詳しくは、[ドキュメント](https://github.com/trallnag/prometheus-fastapi-instrumentator#creating-new-metrics)を参照してください。

### Prometheusの設定

これで、Prometheusでこれらのメトリクスをスクレイピングして収集できます。

各サービスからメトリクスを収集するようにPrometheusを設定できます。デフォルトでは、Prometheusは`/metrics`パスでメトリクスをチェックします：

```
global:
  scrape_interval: 15s
  evaluation_interval: 15s

scrape_configs:
  - job_name: "prometheus"
    static_configs:
      - targets: ["localhost:9090"]
  
  - job_name: "go-app"
    static_configs:
      - targets: ["go-app:8080"]

  - job_name: "python-app"
    static_configs:
      - targets: ["python-app:8000"]

  - job_name: "apisix"
    static_configs:
      - targets: ["apisix:9080"]
    metrics_path: "/prometheus/metrics"
```

これで完了です！Prometheusダッシュボード（デフォルトではポート`9090`）を開き、ナビゲーションバーから「Status」をクリックし、「Targets」を選択すると、サービスからスクレイピングされたメトリクスのステータスを確認できます。

![prometheus-target-status.png](https://static.api7.ai/2022/12/02/6389c097a4d0b.png?imageMogr2/format/webp)

## Prometheusでメトリクスをクエリして視覚化する

これで、Prometheusダッシュボードを使用してクエリや複雑な式を実行できます。

![prometheus-query.png](https://static.api7.ai/2022/12/02/6389c098d5488.png?imageMogr2/format/webp)

Prometheusのクエリについて詳しくは、[公式ドキュメント](https://prometheus.io/docs/prometheus/latest/querying/basics/)を参照してください。

## Grafanaを使用してPrometheusをクエリする

Grafanaは、Prometheusと連携してメトリクスを収集、クエリ、視覚化するための包括的なツールを提供するオープンソースのデータ視覚化プラットフォームです。

Prometheusはメトリクスの収集とクエリに優れていますが、意味のある視覚化を作成するためのツールが不足しています。Grafanaはこの制限を克服し、収集されたメトリクスを視覚化に変換します。

Grafanaは、Prometheus以外にも[多くのデータソース](https://grafana.com/grafana/plugins/?type=datasource)と互換性があります。

Grafanaをデプロイしたら、Web UI（デフォルトではポート`3000`）を開きます。

まず、Prometheusをデータソースとして追加する必要があります。これを行うには、`/datasources`または「Configuration」と「Data sources」に移動します。「Add data source」をクリックし、Prometheusを選択します。Prometheusがデプロイされている場所を指定し、接続を保存してテストします。

![grafana-add-prometheus.png](https://static.api7.ai/2022/12/02/6389c09bbbf5a.png?imageMogr2/format/webp)

### 事前構築済みのGrafanaダッシュボードを使用する

Grafanaは、事前構築済みのGrafanaダッシュボードを含む[公開ダッシュボードリポジトリ](https://grafana.com/grafana/dashboards/)をホストしています。これらのダッシュボードを使用して、関連するメトリクスを迅速に視覚化できます。

このチュートリアルでは、Prometheus Goクライアントライブラリによって公開されたプロセスステータスを処理して視覚化する[Go Processes](https://grafana.com/grafana/dashboards/6671-go-processes/)ダッシュボードを使用します。

このテンプレートをインポートするには、まずダッシュボードリポジトリからそのID（`6671`）をコピーします。Grafana UIで、「Dashboards」に移動し、「Import」を選択します。コピーしたIDを貼り付け、「Load」をクリックします。

![grafana-dashboard.png](https://static.api7.ai/2022/12/02/6389c09b4f15b.png?imageMogr2/format/webp)

他の事前構築済みのダッシュボードを探索したり、独自のダッシュボードを作成したりすることもできます。これについて詳しくは、[ドキュメント](https://grafana.com/blog/2022/06/06/grafana-dashboards-a-complete-guide-to-all-the-different-types-you-can-build/)を参照してください。

## 次のステップ

このチュートリアルは以上です！

この記事は、サービスに監視を設定する方法の紹介に過ぎません。以下のリソースからPrometheusとGrafanaについてさらに学ぶことをお勧めします：

- [Prometheus Best Practices](https://prometheus.io/docs/practices/naming/)
- [Alerting based on metrics](https://prometheus.io/docs/tutorials/alerting_based_on_metrics/)
- [Grafana Dashboards](https://grafana.com/docs/grafana/latest/dashboards/)

このチュートリアルの完全なコードとDocker Composeファイルは、[pottekkat/monitoring-101](https://github.com/pottekkat/monitoring-101)で入手できます。

Tags:

[Monitoring](https://api7.ai/tags/monitoring)

[Prometheus](https://api7.ai/tags/prometheus)

[Grafana](https://api7.ai/tags/grafana)

Share article link

Share

Related Posts

[![API 可观测性提升系列（第3部分）：Tracing](https://static.api7.ai/uploads/2024/03/19/6P6NCsEG_tracing.png)](https://api7.ai/blog/tracing-of-observability-series)

## [API 可观测性提升系列（第3部分）：Tracing](https://api7.ai/blog/tracing-of-observability-series)

[![API 可观测性向上シリーズ（第2回）：ログ分析](https://static.api7.ai/uploads/2024/12/25/ovzwtD1L_log-analysis.png)](https://api7.ai/blog/log-analysis-of-observability-series)

## [API 可观测性向上シリーズ（第2回）：ログ分析](https://api7.ai/blog/log-analysis-of-observability-series)

Table of Contents

- [Prometheusの基本](#prometheus%E3%81%AE%E5%9F%BA%E6%9C%AC)

  - [メトリクスの種類](#%E3%83%A1%E3%83%88%E3%83%AA%E3%82%AF%E3%82%B9%E3%81%AE%E7%A8%AE%E9%A1%9E)

- [サンプルアプリケーション](#%E3%82%B5%E3%83%B3%E3%83%97%E3%83%AB%E3%82%A2%E3%83%97%E3%83%AA%E3%82%B1%E3%83%BC%E3%82%B7%E3%83%A7%E3%83%B3)

- [Prometheusを設定してメトリクスを収集する](#prometheus%E3%82%92%E8%A8%AD%E5%AE%9A%E3%81%97%E3%81%A6%E3%83%A1%E3%83%88%E3%83%AA%E3%82%AF%E3%82%B9%E3%82%92%E5%8F%8E%E9%9B%86%E3%81%99%E3%82%8B)

  - [APISIXからメトリクスをエクスポートする](#apisix%E3%81%8B%E3%82%89%E3%83%A1%E3%83%88%E3%83%AA%E3%82%AF%E3%82%B9%E3%82%92%E3%82%A8%E3%82%AF%E3%82%B9%E3%83%9D%E3%83%BC%E3%83%88%E3%81%99%E3%82%8B)
  - [Goサービスからメトリクスを計装してエクスポートする](#go%E3%82%B5%E3%83%BC%E3%83%93%E3%82%B9%E3%81%8B%E3%82%89%E3%83%A1%E3%83%88%E3%83%AA%E3%82%AF%E3%82%B9%E3%82%92%E8%A8%88%E8%A3%85%E3%81%97%E3%81%A6%E3%82%A8%E3%82%AF%E3%82%B9%E3%83%9D%E3%83%BC%E3%83%88%E3%81%99%E3%82%8B)
  - [Pythonサービスからメトリクスを計装してエクスポートする](#python%E3%82%B5%E3%83%BC%E3%83%93%E3%82%B9%E3%81%8B%E3%82%89%E3%83%A1%E3%83%88%E3%83%AA%E3%82%AF%E3%82%B9%E3%82%92%E8%A8%88%E8%A3%85%E3%81%97%E3%81%A6%E3%82%A8%E3%82%AF%E3%82%B9%E3%83%9D%E3%83%BC%E3%83%88%E3%81%99%E3%82%8B)
  - [Prometheusの設定](#prometheus%E3%81%AE%E8%A8%AD%E5%AE%9A)

- [Prometheusでメトリクスをクエリして視覚化する](#prometheus%E3%81%A7%E3%83%A1%E3%83%88%E3%83%AA%E3%82%AF%E3%82%B9%E3%82%92%E3%82%AF%E3%82%A8%E3%83%AA%E3%81%97%E3%81%A6%E8%A6%96%E8%A6%9A%E5%8C%96%E3%81%99%E3%82%8B)

- [Grafanaを使用してPrometheusをクエリする](#grafana%E3%82%92%E4%BD%BF%E7%94%A8%E3%81%97%E3%81%A6prometheus%E3%82%92%E3%82%AF%E3%82%A8%E3%83%AA%E3%81%99%E3%82%8B)

  - [事前構築済みのGrafanaダッシュボードを使用する](#%E4%BA%8B%E5%89%8D%E6%A7%8B%E7%AF%89%E6%B8%88%E3%81%BF%E3%81%AEgrafana%E3%83%80%E3%83%83%E3%82%B7%E3%83%A5%E3%83%9C%E3%83%BC%E3%83%89%E3%82%92%E4%BD%BF%E7%94%A8%E3%81%99%E3%82%8B)

- [次のステップ](#%E6%AC%A1%E3%81%AE%E3%82%B9%E3%83%86%E3%83%83%E3%83%97)

## Related Posts

[![Apache APISIX 与 open-appsec WAF 集成](https://static.api7.ai/uploads/2024/10/18/8d1iVJWL_logo%20x%20open-appsec.png)](https://api7.ai/ja/blog/apisix-integrates-with-open-appsec-waf)

Ecosystem

October 21, 2024

#### [Apache APISIX 与 open-appsec WAF 集成](https://api7.ai/ja/blog/apisix-integrates-with-open-appsec-waf)

Apache APISIX で公開されている Web API やアプリケーションを、既知および未知の攻撃から保護しましょう。open-appsec を使用して、機械学習ベースの自動 WAF でセキュリティを強化します。

[WAF](https://api7.ai/tags/waf)

[API Security](https://api7.ai/tags/api-security)

[Data Security](https://api7.ai/tags/data-security)

[![IMシステムとのアラート通知の統合](https://static.api7.ai/uploads/2024/04/24/jXjhJxVk_im-cover.png)](https://api7.ai/ja/blog/integrate-api7-alerting-with-im)

Products

April 24, 2024

#### [IMシステムとのアラート通知の統合](https://api7.ai/ja/blog/integrate-api7-alerting-with-im)

API7 Enterpriseを使用してアラートを設定し、Webhook通知を通じて一般的なIMシステムに迅速にアラート通知をプッシュする方法を学びます。

[Monitoring](https://api7.ai/tags/monitoring)

[API Security](https://api7.ai/tags/api-security)

[![APISIXのhttp-loggerプラグインによる簡素化されたログ収集](https://static.api7.ai/uploads/2024/04/11/Zod2vE0f_http-logger-cover.png)](https://api7.ai/ja/blog/apisix-http-logger-plugin)

Technology

April 11, 2024

#### [APISIXのhttp-loggerプラグインによる簡素化されたログ収集](https://api7.ai/ja/blog/apisix-http-logger-plugin)

Learn how to enhance development efficiency with real-time API call log monitoring using the APISIX http-logger plugin.

[Observability](https://api7.ai/tags/observability)

[Monitoring](https://api7.ai/tags/monitoring)

[APISIX Basics](https://api7.ai/tags/apisix-basics)
