本文总结了在处理
在使用日本CN2出口时,经常遇到的痛点包括突发
下面是一个常见的双向限速实操脚本:使用ifb将入站流量重定向到虚拟设备,然后在 ifb 上使用 HTB 做精细带宽分配,同时用 iptables 打标流量以便按源/目的 IP 划分速率。
#!/bin/bash
IFACE=eth0
IFB=ifb0
# 启用 ifb 模块
modprobe ifb numifbs=1
ip link add dev ${IFB} type ifb
ip link set dev ${IFB} up
# 清理旧规则
tc qdisc del dev ${IFACE} root 2>/dev/null || true
tc qdisc del dev ${IFACE} ingress 2>/dev/null || true
tc qdisc del dev ${IFB} root 2>/dev/null || true
# 出站(上传)HTB 在物理设备上
tc qdisc add dev ${IFACE} root handle 1: htb default 30
tc class add dev ${IFACE} parent 1: classid 1:1 htb rate 100mbit ceil 100mbit
tc class add dev ${IFACE} parent 1:1 classid 1:10 htb rate 80mbit ceil 100mbit
tc class add dev ${IFACE} parent 1:1 classid 1:30 htb rate 20mbit ceil 100mbit
tc qdisc add dev ${IFACE} parent 1:10 handle 10: fq_codel
tc qdisc add dev ${IFACE} parent 1:30 handle 30: fq_codel
# 入站(下载)重定向到 ifb
tc qdisc add dev ${IFACE} ingress
tc filter add dev ${IFACE} parent ffff: protocol ip u32 match u32 0 0 action mirred egress redirect dev ${IFB}
# 在 ifb 上做 HTB
tc qdisc add dev ${IFB} root handle 1: htb default 30
tc class add dev ${IFB} parent 1: classid 1:1 htb rate 200mbit ceil 200mbit
tc class add dev ${IFB} parent 1:1 classid 1:10 htb rate 160mbit ceil 200mbit
tc class add dev ${IFB} parent 1:1 classid 1:30 htb rate 40mbit ceil 200mbit
tc qdisc add dev ${IFB} parent 1:10 handle 10: fq_codel
tc qdisc add dev ${IFB} parent 1:30 handle 30: fq_codel
# iptables 标记示例:对特定IP段打 mark=10(走高带宽类)
iptables -t mangle -A PREROUTING -s 203.0.113.0/24 -j MARK --set-mark 10
# 以 mark 匹配 tc filter
tc filter add dev ${IFB} parent 1: protocol ip handle 10 fw classid 1:10
tc filter add dev ${IFB} parent 1: protocol ip handle 30 fw classid 1:30
脚本中关键词已用tc、ifb、HTB、fq_codel和iptables标注,适合用于
除了内核与队列层面的限速,还需在应用层做保护:在Nginx上使用 limit_zone 和 limit_req_zone 做HTTP请求限流;对TCP服务可用 haproxy 做连接数与速率控制。示例(Nginx):
http {
limit_conn_zone $binary_remote_addr zone=addr:10m;
limit_req_zone $binary_remote_addr zone=req:10m rate=30r/s;
server {
location / {
limit_conn addr 10;
limit_req zone=req burst=20 nodelay;
}
}
}
同时必须部署监控与自动化脚本:使用 vnstat、iftop、bmon 监测实时带宽,写一个守护脚本定期检查 /sys/class/net/eth0/statistics/rx_bytes 与 tx_bytes,当短时速率超过阈值时自动放大或缩小 tc class 的 ceil,或临时把恶意IP加入iptables黑名单并上报上游。对于大规模