How to: Quick and Dirty Web Server Load Balancing with IPTables in Linux

Load balancing is a method to distribute workload across multiple computer over a network. The purpose of load balance in web server is to avoid one web server from being overwhelmed by requests which eventually leads the machine to come down to a crawling halt.

Assuming that you have 3 web server to assign the load to each with this IP Address:

You can drive the traffic to each of this on every third packet with this iptables rules:

iptables -A PREROUTING -i eth0 -p tcp --dport 80 -m state --state NEW -m nth --counter 0 --every 3 --packet 0 -j DNAT --to-destination

iptables -A PREROUTING -i eth0 -p tcp --dport 80 -m state --state NEW -m nth --counter 0 --every 3 --packet 1 -j DNAT --to-destination

iptables -A PREROUTING -i eth0 -p tcp --dport 80 -m state --state NEW -m nth --counter 0 --every 3 --packet 2 -j DNAT --to-destination

This will ensure that every 3rd packet of the request will be properly distributed among the three servers to balance the load. Note that this is only useful in simple website which serves static content or for a download servers that serve large files over the internet (CD or DVD iso downloading)

Iptables rule to safeguard SSH server from crackers

Secured Shell or SSH is a service to enable users to access remote system securely. However, SSH servers depending on password-based authentication might be vulnerable to dictionary-based (or brute-force) attacks by crackers.

Luckily iptables can be used with ‘–limit-burst‘ and ‘–limit’ option to reduce the number of attempts and connection that a cracking tool can make in a period of time.

For example, in order to limit an IP address to making only 5 connections per minute in burst of 2 connections, you can use this iptables rules:

iptables -A INPUT -p tcp --dport ssh -m limit --limit 5/minute --limit-burst 2 -j ACCEPT

This will result in the iptables will only allow up to 5 connections per minute with 2 maximum initial number of connections, which will make any brute-force or dictionary-based attack uneconomical/unfeasible for the server.

Read more about iptables –limit and –limit-burst in Linux Iptables Limit the number of incoming tcp connection / syn-flood attacks