通過腳本定時監測docker容器的網路連線狀態
目前有以下三種思路,再通過chatGPT的幫助直接寫完XD
第一種,通過ping工具
#!/bin/bash
# 尋找正在運行的 nginx 容器
id=$(docker ps -a | grep nginx | awk '{print $1}')
# 進入容器
docker exec -it $id /bin/bash
# 安裝 ping 套件
apt-get update && apt-get install -y iputils-ping
# 測試網路連接
if ping -c 6 8.8.8.8 &> /dev/null
then
echo "正常"
else
echo "網路連接失敗,執行 123.sh"
sh 123.sh
fi
第二種,通過stats狀態的NET流量
#!/bin/bash
# 容器名稱
CONTAINER_NAME=<CONTAINER_NAME>
# 每個容器的網路流量,篩選出容器的網路資訊
docker stats --no-stream --format "table {{.Container}}\t{{.NetIO}}\t{{.BlockIO}}" | grep $CONTAINER_NAME > container_net_info.txt
# 取得容器內網路資訊
CONTAINER_NETWORK=$(cat container_net_info.txt | awk '{print $2}')
# 取得容器內接收的Bytes
RECEIVED_BYTES=$(echo $CONTAINER_NETWORK | awk -F '/' '{print $1}')
# 如果接收的Bytes > 0,表示網路連接正常
if [ $RECEIVED_BYTES -gt 0 ]
then
echo "網路連接正常"
else
echo "網路連接異常,執行 123.sh"
sh 123.sh
fi
# 刪除暫存檔案
rm -rf container_net_info.txt
第三種,通過netstat的網路監聽狀態
#!/bin/bash
# 進入容器
docker exec -it <CONTAINER_ID> /bin/bash
# 測試網路連接
ping -c 1 8.8.8.8
# 檢查網路連接狀態
netstat -an | grep 8.8.8.8 | grep -E 'ESTABLISHED|SYN_SENT'
if [ $? -eq 0 ]
then
echo "網路連接正常"
else
echo "網路連接異常,執行 123.sh"
sh 123.sh
fi
補充:
部分docker環境由於最小化原則沒有內建小工具,需要額外安裝:ping、telnet、netstat…等。