Bash
1 前言
一个问题,一篇文章,一出故事。
今天想分析容器的资源使用情况,于是整理此文。
2 最佳实践
2.1 创建脚本目录
mkdir ~/scripts
2.2 创建脚本
vim ~/scripts/monitorContainer.sh
加入如下配置,
#!/bin/bash
monitorLog="/var/log/monitorContainer.log"
monitorDate=`date +"%Y-%m-%d %H:%M:%S"`
containerID="`docker container ls | grep mes-platform_sdc | tail -n 1 | cut -d" " -f1`"
if [ ! -f "$monitorLog" ]; then
touch "$monitorLog"
fi
if [ ! -f "$monitorLog" ]; then
echo "$monitorDate"' Failed to create log file!'
exit 1
fi
#netstat
netStat="`docker exec --user root $containerID /bin/bash -c 'netstat -antp'`"
# list mem and cpu
mem="`docker exec --user root $containerID /bin/bash -c 'free -h'`"
cpu="`docker exec --user root $containerID /bin/bash -c 'top -bn 1 -i -c'`"
# list open file
lsOpenFile="`docker exec --user root $containerID /bin/bash -c 'lsof | wc -l'`"
echo "$monitorDate"' Net Status Time Wait: '`echo "$netStat" | grep -i TIME_WAIT | wc -l` | tee -a "$monitorLog"
echo "$monitorDate"' Net Status Established: '`echo "$netStat" | grep -i ESTABLISHED | wc -l` | tee -a "$monitorLog"
echo "$monitorDate"' Net Status Listen: '`echo "$netStat" | grep -i LISTEN | wc -l` | tee -a "$monitorLog"
echo "$monitorDate"' Net Status Other: '`echo "$netStat" | egrep -iv 'TIME_WAIT|ESTABLISHED|LISTEN' | wc -l` | tee -a "$monitorLog"
echo "$monitorDate"' List Open File: '`echo "$lsOpenFile"` | tee -a "$monitorLog"
echo "$monitorDate" | tee -a "$monitorLog"
echo "$mem" | tee -a "$monitorLog"
echo "$monitorDate" | tee -a "$monitorLog"
echo "$cpu" | tee -a "$monitorLog"
需要注意的是,
– 参数“containerID”声明获取容器ID的命令行
– 参数“monitorLog”声明脚本运行日志路径
2.3 设置脚本触发
crontab -e
加入如下设置,
*/10 * * * * sh ~/scripts/monitorContainer.sh
参阅文档
====================
https://stackoverflow.com/questions/37089033/docker-exec-is-not-working-in-cron
没有评论