Simple load balancing using iptables nth mode of t

2019-05-30 14:42发布

问题:

I am trying to use iptables for load balancing. I'm working with virtualbox. All VMs (debian) are in an internal network and IPs are static. I want to route requests coming to my web server (apache2) with IP address 10.0.0.2:80 to IP addresses of the servers 10.0.0.3:80 and 192.168.0.2:80 on the other network. The network is constructed as such:
The gateway does IP forwarding, it has two interfaces: eth0 used for network 10.0.0.0 and eth1 for network 192.168.0.0. Then there is a load balancer with IP address 10.0.0.2. I've tried to set these rules but they didn't work:

iptables -t nat -A PREROUTING -p tcp --dport 80 -m state --state NEW -m statistic --mode nth --every 3 --packet 0 -j DNAT --to-destination 10.0.0.3:80    
iptables -t nat -A PREROUTING -p tcp --dport 80 -m state --state NEW -m statistic --mode nth --every 3 --packet 1 -j DNAT --to-destination 192.168.0.2:80

回答1:

First of all, since in your case the incoming connection should be distributed across 2 servers, one would have expected a similar solution to the one suggested, but with --every 2, rather than --every 3, to work.

However, as this answer suggests, when the nth mode was made part of the statistic module (in the past it was a separate module), the packet counter was modified from a global one to many individual ones, one per rule.

Therefore, the following should work:

iptables -t nat -A PREROUTING -p tcp --dport 80 -m state --state NEW -m statistic --mode nth --every 2 --packet 0 -j DNAT --to-destination 10.0.0.3:80
iptables -t nat -A PREROUTING -p tcp --dport 80 -m state --state NEW -m statistic --mode nth --every 1 --packet 0 -j DNAT --to-destination 192.168.0.2:80

Of course there is no actual need for use of the statistic module in the second rule, but I've placed it there for future reference in order to clarify how the rules should be constructed if the incoming connections were to be distributed across 3 or more servers, rather than just 2.



标签: iptables