docker + prom + grafana + altermanager

ドッカーの基本

docker run -it --name centos -v $HOME:/tmp -p 8080:8080 centos
docker inspect container   #查看已启动容器启动命令
docker container prune    #删除退出的容器
docker ps -a --no-trunc    #查看容器启动参数

dockerfileを逆チェックします

方法一:
docker history --format {{.CreatedBy}} --no-trunc=true 0e0218889c33|sed "s?/bin/sh\ -c\ \#(nop)\ ??g"|sed "s?/bin/sh\ -c?RUN?g" | tac

方法二:
apt-get install npm    #管理前端包工具
npm install npx
npx dockerfile-from-image node:8 > dockerfile   #解析dockerfile

コンテナイメージの起動コマンドを変更します-dockerは起動コマンドを変更します

#使用宿主机网络,并将容器名称修改为prometheus,-d后台运行
docker run -d -p 9090:9090 --name prometheus --net=host prom/prometheus

#将容器里文件拷贝出来到root目录
docker cp prometheus:/etc/prometheus/prometheus.yml /root/

#修改后挂载加进去
docker run -d -v /opt/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml   \
-p 9090:9090 --name prometheus --net=host prom/prometheus

docker logs contianid   #查看日志
docker search  java    #从docker hub中搜索java镜像,可以查看版本

コンテナポート

9100ノード-エクスポート
9090プロメテウス
3000グラファナ

起動

  • node-exporterを起動します
docker run -d --name=node-exporter -p 9100:9100 prom/node-exporter
  • グラファナを開始

    密码:admin,admin;配置文件/etc/grafana
    docker run -d --name=grafana -p 3000:3000 grafana/grafana
  • ウエディングを開始
    
    #将容器里文件拷贝出来到root目录
    docker cp prometheus:/etc/prometheus/prometheus.yml /root/


変更後、マウントをdocker run -d -v /opt/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml \
-p 9090:9090 --name prometheus --net = host prom / prometheusに追加します。


# docker 镜像自启动
- 在运行docker容器时可以加如下参数来保证每次docker服务重启后容器也自动重启:

docker run --restart = always
起動している場合は、次のコマンドを使用できます
。dockerupdate --restart = always <CONTAINER ID>


# 配置文件
## prom配置
配置帮助
```yaml

global:
  #默认情况下抓取目标的频率.
  [ scrape_interval: <duration> | default = 1m ]

  # 抓取超时时间.
  [ scrape_timeout: <duration> | default = 10s ]

  # 评估规则的频率.
  [ evaluation_interval: <duration> | default = 1m ]

  # 与外部系统通信时添加到任何时间序列或警报的标签
  #(联合,远程存储,Alertma# nager).
  external_labels:
    [ <labelname>: <labelvalue> ... ]

# 规则文件指定了一个globs列表. 
# 从所有匹配的文件中读取规则和警报.
rule_files:
  [ - <filepath_glob> ... ]

# 抓取配置列表.
scrape_configs:
  [ - <scrape_config> ... ]

# 警报指定与Alertmanager相关的设置.
alerting:
  alert_relabel_configs:
    [ - <relabel_config> ... ]
  alertmanagers:
    [ - <alertmanager_config> ... ]

# 与远程写入功能相关的设置.
remote_write:
  [ - <remote_write> ... ]

# 与远程读取功能相关的设置.
remote_read:
  [ - <remote_read> ... ]

具体配置

root@ubuntu:~# cat prometheus.yml 
# my global config
global:
  scrape_interval:     15s # Set the scrape interval to every 15 seconds. Default is every 1 minute.
  evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute.
  # scrape_timeout is set to the global default (10s).

# Alertmanager configuration
alerting:
  alertmanagers:
  - static_configs:
    - targets:
      # - alertmanager:9093

# Load rules once and periodically evaluate them according to the global 'evaluation_interval'.
rule_files:
  # - "first_rules.yml"
  # - "second_rules.yml"

# A scrape configuration containing exactly one endpoint to scrape:
# Here it's Prometheus itself.
scrape_configs:
  # The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
    # metrics_path defaults to '/metrics'
    # scheme defaults to 'http'.

  - job_name: prometheus
    static_configs:
    - targets: ['192.168.191.128:9090']
      labels:
        instance: prometheus
  - job_name: 'consul' #prometheus与consul配置段
    consul_sd_configs:
      - server: '192.168.191.128:8500'
        services: [ ]
  - job_name: node-exporter
    static_configs:
    - targets: ['192.168.191.128:9100']
      labels:
        instance: node-exporter

動的構成file_sd_config:

  • /usr/local/prometheus/*.jsonを変更して追加および削除し、動的更新をサポートします
    
    在prometheus.yaml配置文件最后增加
    - job_name: 'node-discorvery'   #发现规则名称
    file_sd_configs:                       #选择适配器
      - files: 
        - /usr/local/prometheus/*.json   #匹配文件

対応するディレクトリ/usr/local/prometheus/*.jsonに追加すると、コンテナの起動時にマウントする必要があります。
[
{
"targets":["10.10.2.99:9100"]、
"labels":{
"job": "linux- bj "、
" idc ":" bj-jiuxianqiao "
}
}、
{
"ターゲット ":[" 10.10.2.62:9100 "、
" 10.10.1.35:9100 "]、"ラベル ":{
"ジョブ ":" linux- gx "、
" idc ":" gz-daxuecheng "
}
}
]


## rule_files:配置
- 配置告警规则,在prometheus.yml中指定规则文件目录
- prometheus根据这些规则信息,会推送报警信息到alertmanager中。
```yaml

alertmanager_config:構成

  • Prometheusサーバーがアラートを送信するAlertmanagerインスタンスを指定します
  • これらのAlertmanagerとの通信方法を構成するためのパラメーターを提供します。
  • Alertmanagersは、静的指定または動的検出指定をサポートします
  • relabel_configsを使用すると、検出されたエンティティからAlertmanagersを選択し、使用されるAPIパスに高度な変更を加えることができます。これは__alerts_path__ラベルを通じて公開されます。
    # Alertmanager configuration   #告警配置
    alerting:
    alertmanagers:  
    - static_configs:  #告警规则,也可以基于动态的方式进行告警。
    - targets:     
      # - alertmanager:9093

remote_write

バックエンドストレージの書き込みAPIアドレスを指定します。

remote_read

バックエンドのストレージ読み取りAPIアドレスを指定します。

relabel_config

  • 再ラベル付けは、ターゲットをクロールする前にターゲットのタグセットを動的に書き換えることができる強力なツールです。各クロール構成は、複数の再マーキング手順で構成できます。これらは、構成ファイルに表示される順序で各ターゲットのタグセットに適用されます。デフォルトでは、prometheusWebコンソールに関連するタグが表示されます。
    docker + prom + grafana + altermanager

使用する

プロムテウスの使用

docker + prom + grafana + altermanager

node_cpu_seconds_total {cpu = "0"}
docker + prom + grafana + altermanager

grafana使用

grafanaのダッシュボードアドレス

プロメテウスエクスポーター

プロセスエクスポータープロセスモニタリング

docker search process-exporter   #查看排名最高的
docker pull opvizorpa/process-exporter   #下载
docker inspect 9ec6749205fc      #查看镜像启动配置信息:9256端口
apt-get install nginx         #安装nginx测试

docker run -d --rm -p 9256:9256 --privileged -v /proc:/host/proc -v `pwd`:/config ncabatoff/process-exporter --procfs /host/proc -config.path /config/filename.yml

# 本地安装
[root@host-10-10-2-62 ~]# wget https://github.com/ncabatoff/process-exporter/releases/download/v0.5.0/process-exporter-0.5.0.linux-amd64.tar.gz
[root@host-10-10-2-62 ~]# tar -xf process-exporter-0.5.0.linux-amd64.tar.gz -C /usr/local/

# 开机自启动
[root@host-10-10-2-62 process-exporter-0.5.0.linux-amd64]# cat /etc/systemd/system/process-exporter.service 
[Unit]
Description=node exporter
Documentation=node exporter

[Service]
ExecStart=/usr/local/process-exporter-0.5.0.linux-amd64/process-exporter -config.path /usr/local/process-exporter-0.5.0.linux-amd64/process-name.yaml 

[Install]
WantedBy=multi-user.target

# 配置文件根据变量名匹配到配置文件:  
{{.Comm}} 包含原始可执行文件的basename,/proc/stat 中的换句话说,2nd 字段  
{{.ExeBase}} 包含可执行文件的basename  
{{.ExeFull}} 包含可执行文件的完全限定路径  
{{.Matches}} 映射包含应用命令行tlb所产生的所有匹配项

# 增加监控nginx配置文件
root@ubuntu:~# cat process-name.yaml 
process_names:
  - name: "{{.Matches}}"
    cmdline:
    - 'nginx'

# 监控所有进程
[root@host-10-10-2-62 process-exporter-0.5.0.linux-amd64]# cat process-name.yaml 
process_names:
  - name: "{{.Comm}}"
    cmdline:
    - '.+'

# prometheus server添加监控
  - job_name: 'process'
    static_configs: 
      - targets: ['10.10.2.62:9256']

# 进程查询
统计有多少个进程数:sum(namedprocess_namegroup_states)

统计有多少个僵尸进程:sum(namedprocess_namegroup_states{state="Zombie"})

プッシュゲートウェイ

構成

プッシュゲートウェイ9091

docker pull prom/pushgateway

docker run -d \
--name=pushgateway \
-p 9091:9091 \
prom/pushgateway

访问ip+9091

prometheus配置文件中prometheus.yml添加target:
  - job_name: pushgateway
    static_configs:
      - targets: ['192.168.191.128:9091']
        labels:
          instance: pushgateway

URL:http://<ip>:9091/metrics/job/<JOBNAME>{/<LABEL_NAME>/<LABEL_VALUE>},

プッシュデータのテスト

echo "some_metric 3.14" | curl --data-binary @- http://192.168.191.128:9091/metrics/job/some_job

# 一次性推送多条数据
cat <<EOF | curl --data-binary @http://192.168.2.14:9091/metrics/job/some_job/instance/some_instance
 # TYPE some_metric counter
 some_metric{label="val1"} 42
# TYPE another_metric gauge
# HELP another_metric Just an example.
another_metric 2398.283
EOF
  • プッシュゲートウェイのデータは通常、ジョブとインスタンスごとにグループ化および分類されているため、これら2つのパラメータが不可欠であることがわかります。

docker + prom + grafana + altermanager

現在のtcp同時接続をカウントし、それらをプッシュゲートウェイにプッシュします

[root@host-10-10-2-109 ~]# cat count_netstat_esat_connections.sh 
#!/bin/bash
instance_name=`hostname -f | cut -d'.' -f1`  #获取本机名,用于后面的的标签
label="count_netstat_established_connections"  #定义key名
count_netstat_established_connections=`netstat -an | grep -i ESTABLISHED | wc -l`  #获取数据的命令
echo "$label: $count_netstat_established_connections"
echo "$label  $count_netstat_established_connections" | curl --data-binary @- http://10.10.2.109:9091/metrics/job/pushgateway_test/instance/$instance_name
  • ドメイン名のラベルは、ラベル名とそれに続く値を表します。Jobの背後にある定義はpushgateway_test(prometheus、ドメイン名の定義と一致)であり、instance_name変数はホスト名を表します。

docker + prom + grafana + altermanager

  • 目を凝らしている人は、ここに何か問題があるように見えるでしょう。送信されたばかりのインジケーターのジョブ名はexported_job = "pushgateway_test"で、ジョブはjob = "pushgateway"と表示されます。これは明らかに正しくありません。それでは、この理由は何ですか。実際、これはPrometheus構成のパラメーターhonor_labels(デフォルトはfalse)によって決定されます。
  - job_name: pushgateway
    honor_labels: true
    static_configs:
      - targets: ['10.10.2.109:9091'] 
        labels:
          instance: pushgateway 

docker + prom + grafana + altermanager

Pythonインターフェイスpushgatewayデータプッシュ:

1、安装prometheus\_client模块:
apt install python-pip
pip install prometheus_client

2、简单示例文件:

[root@host-10-10-2-109 ~]# cat client.py 
from prometheus_client import CollectorRegistry, Gauge, push_to_gateway
registry = CollectorRegistry()
g = Gauge('job_last_success_unixtime', 'Last time a batch job successfully finished', registry=registry)
g.set_to_current_time()
push_to_gateway('localhost:9091', job='batchA', registry=registry)
#执行脚本
[root@host-10-10-2-109 ~]# python client.py 

3.クエリ結果:
docker + prom + grafana + altermanager

docker + prom + grafana + altermanager

4.少し変更を加えて、pingデータを取得します。

[root@host-10-10-2-109 ~]# cat client_ping.py 
#!/usr/bin/python
from prometheus_client import CollectorRegistry, Gauge, push_to_gateway
registry = CollectorRegistry()
g = Gauge('ping', 'pingtime',['dst_ip','city'], registry=registry) #Guage(metric_name,HELP,labels_name,registry=registry)
g.labels('192.168.1.10','shenzhen').set(42.2)    #设置标签
g.labels('192.168.1.11','shenzhen').set(41.2)
g.labels('192.168.1.12','shenzhen').set(32.1)  
push_to_gateway('localhost:9091', job='ping_status', registry=registry)
[root@host-10-10-2-109 ~]# python client_ping.py 

docker + prom + grafana + altermanager
docker + prom + grafana + altermanager

promql

範囲ベクトル

  • s-秒
  • m-分
  • h-時間
  • d-日
  • w-週
  • y年のタイムシフト操作:
    prometheus_http_requests_total{handler="/api/v1/query"}[5m]
    prometheus_http_requests_total{} offset 5m #返回5分钟前的样本,瞬时位移
    prometheus_http_requests_total{}[1d] offset 1d  #返回昨天一天的数据样本,区间位移

スカラー浮動小数点値

スカラー浮動小数点値は、フォームに直接書き込むことができます[-](digits)[.(digits)]

例如: 20
スカラーには1つの数値しかなく、タイミングはありません。式count(http_requests_total)を使用する場合、返されるデータタイプは瞬間的なベクトルであることに注意してください。ユーザーは、組み込み関数scalar()を使用して、単一の瞬時ベクトルをスカラーに変換できます。

文字列:文字列

"this is a string"
'these are unescaped: \n \\ \t'
`these are not unescaped: \n ' " \t`

Promql演算子

PromQLを使用して時系列を便利にクエリおよびフィルタリングすることに加えて、PromQLは豊富な演算子もサポートしています。ユーザーはこれらの演算子を使用してイベントシーケンスをさらに処理できます。これらの演算子には、数学演算子、論理演算子、ブール演算子などが含まれます。

計算

PromQLでサポートされているすべての数学演算子は次のとおりです。

 + (加法)
  - (减法)
  * (乘法)
  / (除法)
  % (求余)
  ^ (幂运算)

たとえば、ホストのメモリサイズをクエリすると、Bytesが返されます。Gに変換する場合は、次の式を使用できます。

node_memory_MemTotal_bytes / 1024 /1024 /1024

返される結果は瞬時ベクトルです。2つの瞬間ベクトル間の数学的計算は次のようになります。

node_disk_written_bytes_total + node_disk_read_bytes_total #返回的是多块磁盘之间的读写IO

次に、式のラベルに基づいて数学演算が実行され、それぞれvdaとvdbのディスクioが計算されることがわかります。

ブール演算

PromQLでは、タグマッチングモードを介して、ユーザーは時系列の特徴的な次元に従ってそれらを照会できます。ブール演算を使用すると、ユーザーは時系列のサンプルの値に従って時系列をフィルタリングできます。これは、アラームルールでよく使用されます。

Prometheusは、次のブール演算子をサポートしています。


 == (相等)
 != (不相等)
 > (大于)
 < (小于)
 >= (大于等于)
 <= (小于等于)

bool修飾子を使用して、一致するクエリ結果を返します。

例:数学演算子を使用すると、すべてのホストノードの現在のメモリ使用量を簡単に計算できます。

(node_memory_bytes_total - node_memory_free_bytes_total) / node_memory_bytes_total

アラームルールを作成するときは、メモリ使用量が95%を超えるホストを除外する必要があります。ブール式を使用できます。

(node_memory_bytes_total - node_memory_free_bytes_total) / node_memory_bytes_total &gt; 0.95

セット演算子

瞬時ベクトル式を使用して、複数の時系列を含むセットを取得できます。これを瞬時ベクトルと呼びます。セット操作により、対応するセット操作を2つの瞬時ベクトルと瞬時ベクトル間で実行できます。現在、Prometheusは次のセット演算子をサポートしています。

and (并且)
or (或者)
unless (排除)

vector1とvector2は、vector1の要素で構成される新しいベクトルを生成します。このベクトルには、vector2の要素と完全に一致するvector1の要素が含まれています。

vector1またはvector2は、vector1のすべてのサンプルデータと、vector1と一致しないvector2のサンプルデータを含む新しいベクトルを生成します。

vector2が新しいベクトルを生成しない限り、vector1。新しいベクトルの要素は、vector2と一致しないvector1の要素で構成されます。

オペレーターの優先順位

Prometheusシステムでは、バイナリ演算子の優先順位は高いものから低いものへと次のようになります。

 ^
*, /, %
 +, -
 ==, !=, <=, <, >=, >
 and, unless
or

同じ優先順位の演算子は連想的です(左連想的)。たとえば、2 3%2は(2 3)%2と同等です。演算子^は例外であり、^は右連想性を満たします。たとえば、2 ^ 3 ^ 2は2 ^(3 ^ 2)と同等です。

集約操作

Prometheusには、瞬時ベクトルに作用する次の組み込み集計演算子も用意されています。瞬時式によって返されるサンプルデータを集約して、新しい時系列を形成することができます。

 sum (求和)
 min (最小值)
 max (最大值)
 avg (平均值)
 stddev (标准差)
 stdvar (标准差异)
 count (计数)
 count_values (对value进行计数)
 bottomk (后n条时序)
 topk (前n条时序)
 quantile (分布统计)

集計操作を使用するための構文は次のとおりです。

&lt;aggr-op&gt;([parameter,] &lt;vector expression&gt;) [without|by (&lt;label list&gt;)]

それらの中で、count_values、quantile、topk、およびbottomkのみがパラメーターをサポートします。

withoutは、列挙されたタグを計算結果から削除し、他のタグを保持するために使用されます。Byは逆で、リストされたタグのみが結果ベクトルに保持され、残りのタグは削除されます。サンプルの質問に従って、データを集約することができます。

sum(http_requests_total) without (instance)
等于:
sum(http_requests_total) by (code,handler,job,method)

アプリケーション全体のHTTPリクエストの合計量を計算するだけでよい場合は、次の式を直接使用できます。

sum(http_requests_total)
查询数据的平均值:
avg(http_requests_total)
查询最靠前的3个值:
topk(3, http_requests_total)

共通機能

Prometheusは、さまざまなデータタイプに対して多くの計算関数を提供します。1つの小さなトリックは、カウンターデータタイプに遭遇することです。操作を実行する前に、rate()またはincrease()関数を配置します。理解に役立つ、より一般的に使用される関数を次に示します。

増加()関数

この関数は、カウンターデータタイプとともに使用され、間隔ベクトルの最初と最後のサンプルを取得して、その増加を返します。特定の時間で割ると、その時間の平均成長率を得ることができます。

increase(node_cpu_seconds_total[2m]) / 120 #過去2分間のホストノードの平均CPU使用量

rate()関数

この関数は、カウンタータイプのデータで使用され、この期間のカウンターの1秒あたりの平均増分を取得します。

rate(node_cpu_seconds_total[2m]) #直接计算区间向量在时间窗口内平均增长速率

sum()関数

実際の作業では、ほとんどのCPUはマルチコアであり、node_cpuは各コアのデータを個別に表示します。実際には、各コアの個々の状況ではなく、全体的なCPUの状況を考慮します。sum()関数を使用して合計すると、合計データを取得できますが、sum()はすべてのマシンのデータを合計するため、(インスタンス)または(cluster_name)で再度取り出すことができます。単一サーバーまたはサーバーグループのCPUデータ。上記の式は次のように展開できます。

sum( increase(node_cpu_seconds_total[1m]) ) #先找出每一个,然后再合并

Topk():この関数は、大量のデータから上位N値を抽出でき、Nをカスタマイズできます。たとえば、100台のサーバーの320台のCPUを監視する場合、この関数を使用して、アラームの現在の負荷が高いCPUを表示できます。

topk(3, http_requests_total) #统计最靠前的3个值。

Forecast_linear()関数:曲線の変化率を計算し、特定の予測的役割を果たします。たとえば、現在の1時間のディスク可用性率が急激に低下している場合、ディスクがすぐにいっぱいになる可能性があります。このとき、この機能を使用して、現在の1時間のデータで次の数時間の状態を予測し、早期警告を実現できます。 :

predict_linear( node_filesystem_free_bytes{mountpoint="/"}[1h],4*3600 ) &lt; 0 #如果未来4小时后磁盘使用率为负数就会报警

cpu使用率式の分解

1.最初にキーを見つけて、たとえばCPU使用率を確認してから、node_cpuキーを使用する必要があります

2. node_cpuキーに基づいてアイドル状態のCPU時間とすべてのCPU時間を除外し、フィルタリングに{}を使用します

node_cpu_seconds_total{ mode='idle' }  #找出空闲CPU的值
node_cpu_seconds_total  #不写其他参数代表ALL

3.increase()関数を使用して1分間のデータを取得します。このとき、各CPUのデータが取り出されます。

increase(node_cpu_seconds_totalmode='idle'}[1m])

4. sum()関数を使用して、各CPUのデータを合計し、単一のデータを取得します。

sum( increase(node_cpu_seconds_total{mode='idle'}[1m]) )

5. sum()関数は、各CPUのデータを合計しますが、各サーバーのデータも合計します。すべてのサーバーのCPUデータは同じであるため、1回処理する必要があります。(インスタンス)による新機能が登場します。指定された方法に従って合計された合計の値を分割し、インスタンスはマシン名を表します。(インスタンス)で書き込まない場合は、{}で必要なインスタンスデータを指定する必要があります。

sum( increase(node_cpu_seconds_total{mode='idle'}[1m]) ) by (instance) #空闲CPU一分钟增量

6.CPUアイドル時間のパーセンテージを取得します。

sum(increase(node_cpu_seconds_total{mode="idle"}[1m])) by(instance) /sum(increase(node_cpu_seconds_total[1m])) by(instance)

7. CPU使用率:

1-(sum(increase(node_cpu_seconds_total{mode="idle"}[1m])) by(instance) /sum(increase(node_cpu_seconds_total[1m])) by(instance)) * 100

最終的な計算は負になる可能性があり、多くのグラナファテンプレートは同じになる可能性があります。cpuがマルチコア、低負荷の状況にある場合、値の差が増幅され、負の数になります。

一般的に使用されるいくつかの表現

1.cpuの使用率を計算します。

100 - (avg(irate(node_cpu_seconds_total{mode="idle"}[5m])) by (instance) * 100)

2.メモリ使用量:

(node_memory_MemFree_bytes+node_memory_Cached_bytes+node_memory_Buffers_bytes) / node_memory_MemTotal_bytes * 100

3.ディスク使用量

100 - (node_filesystem_free_bytes{mountpoint="/",fstype=~"ext4|xfs|rootfs"} / node_filesystem_size_bytes{mountpoint="/",fstype=~"ext4|xfs|rootfs"} * 100)

4.ホストノードcpuiowaitのパーセンテージ:
avg(irate(node_cpu_seconds_total{mode="iowait"}[5m])) by (instance) * 100

5. 1分でのシステムの負荷:
sum by (instance) (node_load1)

6.ネットワークカードトラフィック:
avg(irate(node_network_receive_bytes_total{device=~"eth0|eth1|ens33|ens37"}[1m]))by (environment,instance,device)

リファレンスブログ

-Alinodeの公式画像分析とDockerfileの抽出| Webテクノロジーテスト
サイト-dockerのgrafana用のHub.docker.com、公式ヘルプドキュメント
ncabatoff / process-exporter:Prometheus exporter

おすすめ

転載: blog.51cto.com/14223698/2574538