Load balancer through IpTables| 11/18/2011
L o a d b a l a n c e r t h r o u g h I p T a b l e s | 1 1 / 1 8 / 2 0 1 1
Load Balancing through IpTables
iptables is a user space application program that allows a system administrator to configure the tablesprovided by the Linux kernel firewall and the chains and rules it stores. Different kernel modules andprograms are currently used for different protocols; iptables applies to IPv4, ip6tables to IPv6, arptablesto ARP, and ebtables to Ethernet frames.Iptables requires elevated privileges to operate and must be executed by user root, otherwise it fails tofunction. On most Linux systems, iptables is installed as /usr/sbin/iptables and documented in its manpage, which can be opened using man iptables when installed. It may also be found in /sbin/iptables,but since iptables is more like a service rather than an "essential binary", the preferred location remains/usr/sbin.
Load Balancing with Random
This extension allows you to match packets based on a given probability. The first rule from the set of random rules below matches 25% (--average 25) of the TCP connections to port 80 and redirects theseto the first mirrored web server. Of the 75% of connections not matching on the first rule, 25% willmatch the second and a further 25% will match the third. The remaining 25% will be caught by thefourth rule.
A PREROUTING -i eth0 -p tcp --dport 80 -m state --state NEW -m random --average 25 \ -j DNAT --to-destination 192.168.0.5:80-A PREROUTING -i eth0 -p tcp --dport 80 -m state --state NEW -m random --average 25 \ -j DNAT --to-destination 192.168.0.6:80-A PREROUTING -i eth0 -p tcp --dport 80 -m state --state NEW -m random --average 25 \-j DNAT --to-destination 192.168.0.7:80-A PREROUTING -i eth0 -p tcp --dport 80 -m state --state NEW \-j DNAT --to-destination 192.168.0.8:80
Load Balancing with nth
The below four (nth) rules use counter 0 to count every 4th packet. Once the 4th packet is received, thecounter is reset to zero. The first rule matches the 1st packet (--packet 0) of every four counted, thesecond rule matches the 2nd packet (--packet 0), and so on.