Debian – Load balancing iptables

debianiptablesload balancingvirtualbox

I am trying to use iptable for load balancing. I'm working with virtualbox. All vm (debian)are in internal networking and IPs are static. I want to route requests coming to my web server(apache2) with IPaddress 10.0.0.2:80 to IPs of the server 10.0.0.3:80 and 192.168.0.2:80 on the other network.

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. The load balancer has the IP 10.0.0.2. I try to set this rules but it 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

Best Answer

I'd suggest using a different solution like haproxy, an nginx proxy, or nearly any other actual load balancing method. Usually iptables load balancing is used for outgoing packets on multiple uplinks.

If you must balance using iptables, then you need to use a different method. Just every few packets will mangle all your requests. I saw a decent tutorial on a similar setup (here) which "forwards" all odd-numbered source addresses to one host, and all even-numbered addresses to the other. Really, each server gets all the connection requests and traffic, but only one establishes the connection. The servers are given the same MAC address, and then told to drop syn packets from either even or odd numbered sources. This has the benefit of not adding a single point of failure, as long as you script up something to re-allow all traffic on the live one if the other goes down.

Related Topic