有這么一種情況了,使用linux作為一個(ge)網關,假如(ru)有多個(ge)彈性(xing)ip,那么如(ru)何(he)使得經過(guo)網關的流(liu)量從幾(ji)個(ge)彈性(xing)ip分流(liu)出(chu)去呢(ni)
有一種辦法就是解(jie)決使(shi)用(yong)Linux系統自帶的(de)的(de)iptables的(de)statistic match,而(er)不用(yong)引入其他組件
假設有2個彈性ip
必須嚴格按照順序來(否則達不到要的效果) --every 2 --packet 0 在前,--every 1 --packet 0在后面
添加規則
sudo iptables -t nat -A PREROUTING -m state --state NEW -m statistic --mode nth --every 2 --packet 0 -j SNAT --to-destination 10.50.208.92
sudo iptables -t nat -A PREROUTING -m state --state NEW -m statistic --mode nth --every 1 --packet 0 -j SNAT --to-destination 10.50.208.93
刪除規則
sudo iptables -t nat -D PREROUTING -m state --state NEW -m statistic --mode nth --every 2 --packet 0 -j SNAT --to-destination 10.50.208.92
sudo iptables -t nat -D PREROUTING -m state --state NEW -m statistic --mode nth --every 1 --packet 0 -j SNAT --to-destination 10.50.208.93
假設有3個彈性ip
注意規則的順序,由先到后的順序是
--mode nth --every 3 --packet 0
--mode nth --every 2 --packet 0
--mode nth --every 1 --packet 0
sudo iptables -t nat -A PREROUTING -m state --state NEW -m statistic --mode nth --every 3 --packet 0 -j SNAT --to-destination 10.50.208.92
sudo iptables -t nat -A PREROUTING -m state --state NEW -m statistic --mode nth --every 2 --packet 0 -j SNAT --to-destination 10.50.208.93
sudo iptables -t nat -A PREROUTING -m state --state NEW -m statistic --mode nth --every 1 --packet 0 -j SNAT --to-destination 10.50.208.94
刪除規則
sudo iptables -t nat -D PREROUTING -m state --state NEW -m statistic --mode nth --every 3 --packet 0 -j SNAT --to-destination 10.50.208.92
sudo iptables -t nat -D PREROUTING -m state --state NEW -m statistic --mode nth --every 2 --packet 0 -j SNAT --to-destination 10.50.208.93
sudo iptables -t nat -D PREROUTING -m state --state NEW -m statistic --mode nth --every 1 --packet 0 -j SNAT --to-destination 10.50.208.94