温馨提示×

centos iptables怎么集群

小樊
46
2026-09-21 00:02:33
栏目: 智能运维

在 CentOS 上实现 iptables 的“集群”,通常不是指 iptables 本身组成集群,而是指 多台服务器共享/同步 iptables 规则,或者 用 iptables 做集群流量调度(负载均衡)。下面按常见场景给你说明。


一、用 iptables 实现“集群”(流量分发)

如果你是想像 LVS 一样,用 iptables 把流量分发到多台后端服务器:

1. 使用 iptables + statistic 模块(简单轮询)

iptables -t nat -A PREROUTING \
  -p tcp --dport 80 \
  -m statistic --mode nth --every 2 --packet 0 \
  -j DNAT --to-destination 192.168.1.11:80

iptables -t nat -A PREROUTING \
  -p tcp --dport 80 \
  -m statistic --mode nth --every 2 --packet 1 \
  -j DNAT --to-destination 192.168.1.12:80

✅ 适合:

  • 简单负载均衡
  • 测试环境

❌ 不适合:

  • 会话保持
  • 节点健康检查

2. 使用 iptables + clusterip(多播式集群)

CentOS 早期支持 CLUSTERIP

iptables -A INPUT -d 192.168.1.100 -j CLUSTERIP \
  --new --hashmode sourceip \
  --clustermac 01:00:5e:00:00:01 \
  --total-nodes 2 --local-node 1

✅ 适合:

  • 多台服务器共用一个 VIP
  • 无状态服务

❌ 问题:

  • CentOS 7 以后基本废弃
  • 配置复杂

二、多台 CentOS 同步 iptables 规则(规则集群)

如果你是 多台服务器要保持 iptables 规则一致

方案 1:iptables-save / restore + 同步

# 导出
iptables-save > iptables.rules

# 导入
iptables-restore < iptables.rules

配合:

  • rsync
  • ansible
  • cron

✅ 简单可靠
❌ 非实时


方案 2:使用 firewalld(CentOS 7+ 推荐)

CentOS 7/8 默认用 firewalld:

firewall-cmd --add-port=80/tcp --permanent
firewall-cmd --reload

多台同步:

  • Ansible
  • SaltStack
  • Puppet

方案 3:使用 iptables 管理工具

  • ferm
  • shorewall
  • nftables(CentOS 8+ 推荐)

三、真正“集群级”方案(生产推荐)

如果是生产环境,不建议只用 iptables:

  • LVS + keepalived(四层)
  • HAProxy / Nginx(七层)
  • Kubernetes Service
  • nftables + conntrack

四、我可以继续帮你

你可以告诉我:

  1. CentOS 版本(6 / 7 / 8 / Stream)
  2. 规则同步 还是 流量集群
  3. 内网还是公网
  4. 是否有 VIP / 高可用需求

我可以直接给你一套可执行的配置方案。

0