解决 Linux 报错 iptables Memory allocation problem 异常
分析 Linux 在批量下发大规则集或使用 xt_recent 模块时报 iptables Memory allocation problem 的内核参数调优方案。
问题现象
在执行 iptables 规则下发或重启防火墙服务时报错退出:
iptables: Memory allocation problem.
# 或
iptables-restore: line 42 failed: Memory allocation problem
触发根因
xt_recent或conntrack模块预分配的表项容量不足,无法容纳规则集指定的 IP 清单。- 单个 iptables 链中的规则条数庞大(数万条),超过了内核 netfilter 在单次原子替换(Atomic Replace)时分配连续 vmalloc 内存的能力。
解决步骤与操作命令
步骤一:调整 xt_recent 模块内核参数
如果规则中使用了 -m recent 防爆破:
创建 /etc/modprobe.d/iptables.conf:
options xt_recent ip_list_tot=10000 ip_pkt_list_tot=50
重新加载模块生效:
sudo rmmod xt_recent && sudo modprobe xt_recent
步骤二:海量 IP 黑名单改用 ipset(架构优化)
严禁使用数千条单行 iptables 规则匹配 IP,改用 O(1) 复杂度的 ipset:
# 创建黑名单集合
sudo ipset create blacklist hash:net
# 将 IP 批量加入集合
sudo ipset add blacklist 192.168.1.100
# 仅需单条 iptables 规则即可匹配整个集合
sudo iptables -I INPUT -m set --match-set blacklist src -j DROP
步骤三:持久化 ipset 并在开机自动载入
sudo ipset save > /etc/ipset.conf
验证确认
重新加载防火墙规则:
sudo iptables-restore < /etc/iptables.rules
规则在瞬间完成原子加载,内存分配错误消除,系统负载明显下降。


