在 CentOS 上使用 iptables 做“负载均衡”,通常指 DNAT + statistic 模块 实现简单的流量分发(非真正 L4/L7 负载均衡)。下面按常见场景说明。
iptables 本身没有完整负载均衡功能,但可以通过:
DNAT:把请求转发到后端statistic 模块:按概率或轮询方式选择目标适合:
不适合:
echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf
sysctl -p
systemctl stop firewalld
systemctl disable firewalld
假设:
iptables -t nat -A PREROUTING -p tcp --dport 80 \
-m statistic --mode random --probability 0.5 \
-j DNAT --to-destination 10.0.0.1:80
iptables -t nat -A PREROUTING -p tcp --dport 80 \
-j DNAT --to-destination 10.0.0.2:80
说明:
iptables -t nat -A PREROUTING -p tcp --dport 80 \
-m statistic --mode nth --every 2 --packet 0 \
-j DNAT --to-destination 10.0.0.1:80
iptables -t nat -A PREROUTING -p tcp --dport 80 \
-m statistic --mode nth --every 2 --packet 1 \
-j DNAT --to-destination 10.0.0.2:80
否则回包不会经过网关:
iptables -t nat -A POSTROUTING -d 10.0.0.1 -j MASQUERADE
iptables -t nat -A POSTROUTING -d 10.0.0.2 -j MASQUERADE
或统一:
iptables -t nat -A POSTROUTING -j MASQUERADE
iptables -t nat -A PREROUTING -p udp --dport 53 \
-m statistic --mode random --probability 0.5 \
-j DNAT --to-destination 10.0.0.1:53
iptables -t nat -A PREROUTING -p udp --dport 53 \
-j DNAT --to-destination 10.0.0.2:53
service iptables save
# 或
iptables-save > /etc/sysconfig/iptables
如果你能说明:
我可以给你更精确的配置方案。