Saturday, September 4, 2010

netfilter statistics match load balancing

I find that there is a dearth of documentation on the appropriate syntax for the newer netfilter statistics mode match. It seems that it has changed a few times over the years.

/sbin/iptables -t nat -A PREROUTING -p tcp --dport 80 -m state --state NEW -m statistic \
--mode nth --every 3 -j DNAT --to-destination 192.168.1.1:80

/sbin/iptables -t nat -A PREROUTING -p tcp --dport 80 -m state --state NEW -m statistic \
--mode nth --every 2 -j DNAT --to-destination 192.168.1.2:80

/sbin/iptables -t nat -A PREROUTING -p tcp --dport 80 -m state --state NEW -m statistic \
--mode nth --every 1 -j DNAT --to-destination 192.168.1.3:80

To clarify this, each rule is terminating so the match is a probability. Every 3 packets (33%) match the first. Of the remaining 66%, every other (50%) matches the second. And then 1/1 packets (all of em) match the last. This set of rules will DNAT your incoming web traffic evenly across three servers.