0

I am trying to load balance using iptables.

My rules look like below:

iptables -t nat -A PREROUTING -p tcp --dport 5000 -m statistic --mode nth --every 6 --packet 0 -j REDIRECT --to-port 5890

iptables -t nat -A PREROUTING -p tcp --dport 5000 -m statistic --mode nth --every 5 --packet 0 -j REDIRECT --to-port 5891

.

.

.

iptables -t nat -A PREROUTING -p tcp --dport 5000 -m statistic --mode nth --every 1 --packet 0 -j REDIRECT --to-port 5896

Can I use multiport option to consolidate the six rules into a single one?

  • are you sure there's not a cut/paste error? same destination port and same redirection port for every rule... I don't see how there's any load-balancing done with this configuration. Also a REDIRECTed destination is always local (the system running iptables) and won't be routed. Is that what you want for load-balancing? – A.B Jan 17 '18 at 18:45
  • corrected, that was a typo. my intention is to redirect any packet that comes to 5000 to six other ports in a round robin way. In a way its internal port load balancing – Mystic monk Jan 19 '18 at 3:16
0

The multiport match is used as selector. There's no multiport option for the TARGET REDIRECT. If you try to put a port range in the --to-ports option of REDIRECT, only the first port in the range will be chosen. Same if you (manage to) use -j DNAT --to-destination rule instead of REDIRECT. There won't be round-robin used.

The method you're currently using with iptables is certainly the way to go. The only minor optimization I can see is that you don't need -m statistic --mode nth --every 1 --packet 0 on the last rule, because it always matches, and that --packet defaults to 0 so can be omitted everywhere.

Note: an other possible method would be by using ipvs (aka lvs) but it's certainly overkill especially for a local redirection, if at all possible for this case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.