Load balancing by iptables

Yet another awesome feature of iptables is the ability to use it as a crude load balancer.  It can be used in a round robin way which gives administrators an alternative to using DNS in a similar method.

In this example it will use the prerouting table whilst counting packets across three IP addresses.

iptables -A PREROUTING -i eth0 -p tcp –dport 443 -m state –state NEW -m nth –counter 0 –every 3 –packet 0 -j DNAT –to-destination 192.168.1.101:443
iptables -A PREROUTING -i eth0 -p tcp –dport 443 -m state –state NEW -m nth –counter 0 –every 3 –packet 1 -j DNAT –to-destination 192.168.1.102:443
iptables -A PREROUTING -i eth0 -p tcp –dport 443 -m state –state NEW -m nth –counter 0 –every 3 –packet 2 -j DNAT –to-destination 192.168.1.103:443

 

This could be further modified to weight the load balancing across different servers.

Leave a comment