1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

CI/CD Docker コンテナのモニタリング

Posted at

##起動中コンテナのリソース消費状況を表示

$ docker stats --no-stream
CONTAINER ID        NAME                CPU %               MEM USAGE / LIMIT     MEM %               NET I/O             BLOCK I/O           PIDS
a5ed2facaadd        webcentos           0.00%               2.398MiB / 12.37GiB   0.02%               1.31kB / 0B         0B / 0B             2
e3a96695d263        docker_mysql_1      0.12%               187.5MiB / 12.37GiB   1.48%               1.05kB / 0B         0B / 0B             27
cc761f675b3b        docker_nginx_1      0.00%               4.309MiB / 12.37GiB   0.03%               956B / 0B           0B / 0B             2

##フォーマットして表示

$ docker stats --no-stream --format "{{.Name}},{{.MemPerc}},{{.CPUPerc}}"   #コンテナ名, メモリ使用率, CPU使用率
webcentos,0.02%,0.00%
docker_mysql_1,1.48%,0.12%
docker_nginx_1,0.03%,0.00%

##監視バッチ
###1分毎に実行して使用率閾値(80%)を超過したら通知メッセージを飛ばす

#!/bin/bash

# 閾値(%)
LIMIT=90

# コンテナのSTATS取得
CHECK_STATS=$(docker stats --no-stream --format "{{.Name}},{{.MemPerc}},{{.CPUPerc}}") #コンテナ名, メモリ使用率, CPU使用率

while read row; do
  name=`echo ${row} | cut -d , -f 1`     #コンテナ名
  memPer=`echo ${row} | cut -d , -f 2`   #メモリ使用率
  memPer_i=`echo ${memPer%%.*}`
  cpuPer=`echo ${row} | cut -d , -f 3`   #CPU使用率
  cpuPer_i=`echo ${cpuPer%%.*}`
  
  # メモリ使用率閾値チェック
  if [ $memPer_i -ge $LIMIT ]; then
     message="Container:${name} Memory alert ${memPer}"
     curl -X POST --data-urlencode 'payload={"channel": "#alert", "username": "admin", "text": "${message}"}' <webhook URL>
  fi

  # CPU使用率閾値チェック
  if [ $cpuPer_i -ge $LIMIT ]; then
     message="Container:${name} CPU alert ${cpuPer}"
     curl -X POST --data-urlencode 'payload={"channel": "#alert", "username": "admin", "text": "${message}"}' <webhook URL>
  fi
done < echo "$CHECK_STATS"
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?