检测docker 容器的tcp连接情况,并做统计(window 和mac环境不支持)
用法:./detect.sh
detect.sh 源码如下:
#!/usr/bin/env bash
tmp_result="/tmp/docker_connections";
detectTCPConnection(){
echo "start detecting...";
list=$(docker ps -f 'status=running' --format "table {{.ID}}");
list=${list#CONTAINER ID};
test -z "${list}" && echo "container id is null" && exit 0;
timestamp=$(date +"%Y%m%d%H%M%S");
test ! -d "${tmp_result}" && mkdir ${tmp_result};
cd ${tmp_result};
for i in $list; do
pid=$(docker inspect -f {{.State.Pid}} $i);
echo "start detect for pid:${pid}";
tmpFile="${i}_${pid}.txt";
echo "make file ${tmpFile}";
test -a "$tmpFile" && rm -f $tmpFile;
nsenter -t $pid -n netstat |grep ESTABLISHED > $tmpFile;
echo "end statistic connection for container ${i}";
done
}
doStatisticTCPConection(){
test ! -d "${tmp_result}" && echo "not data for statistic" && exit 0;
cd ${tmp_result};
for i in *.txt; do
echo "${i} tcp connections:$(cat ${i} | grep "6379" | wc -l)";
done
}
select i in 'do detect' 'do statistic' 'do both';do
case $i in
'do detect')
detectTCPConnection;
;;
'do statistic')
doStatisticTCPConection;
;;
'do both')
detectTCPConnection;
doStatisticTCPConection;
;;
*)
echo "usage: ./detect.sh ";
;;
esac
done
使用案例:查看每个容器中redis的连接数
提示:需要详细资料,可以访问这个