當伺服器擁有兩張網卡(eth0、eth1)且指向同一網關時,預設路由會導致所有流量僅從主網卡出入,無法利用雙網卡頻寬。本文記錄透過 iproute2 實現「原路返回」(Source-based Routing)的完整步驟,使進入 eth0 的流量從 eth0 回應,進入 eth1 的流量從 eth1 回應。
iftop 顯示所有流量集中在 eth0,eth1 閒置# 編輯 /etc/iproute2/rt_tables
252 net_eth0
251 net_eth1
# eth0 專屬路由表
ip route flush table net_eth0
ip route add default via 112.253.xx.5 dev eth0 src 112.253.xx.45 table net_eth0
ip rule add from 112.253.xx.45 table net_eth0
# eth1 專屬路由表
ip route flush table net_eth1
ip route add default via 112.253.xx.5 dev eth1 src 112.253.xx.160 table net_eth1
ip rule add from 112.253.xx.160 table net_eth1
將上述指令加入 /etc/rc.local 或 systemd service 實現開機自動生效。
ip rule add from IP table TABLE:根據來源 IP 選擇路由表src IP:指定該路由表發出封包的來源 IP,確保回應封包使用正確介面via 指向對應 ISP 的網關即可# 查看規則
ip rule show
# 查看自訂路由表
ip route show table net_eth0
ip route show table net_eth1
# 即時流量監控
iftop -i eth0
iftop -i eth1
配置完成後,雙網卡流量將均衡分佈,單網關環境下也能發揮雙網卡優勢。