从 iptables 迁移到 nftables

适用场景

新系统或需要原子规则更新、集合匹配和更好性能时,从 iptables 迁移到 nftables。Docker/Kubernetes/fail2ban 等动态写规则的组件要单独评估。

前置条件

步骤

  1. 导出旧规则:
iptables-save > /root/iptables-backup.rules
ip6tables-save > /root/ip6tables-backup.rules
iptables --version
  1. 翻译规则:
iptables-translate -A INPUT -p tcp --dport 22 -j ACCEPT
iptables-translate -t nat -A POSTROUTING -o eth0 -j MASQUERADE
  1. 编写 /etc/nftables.conf:
table inet filter {
  chain input {
    type filter hook input priority 0; policy drop;
    ct state established,related accept
    iif lo accept
    tcp dport 22 accept
    tcp dport { 80, 443 } accept
    icmp type echo-request accept
  }
  chain forward { type filter hook forward priority 0; policy drop; }
  chain output { type filter hook output priority 0; policy accept; }
}
  1. 在测试机验证:
nft -c -f /etc/nftables.conf
nft -f /etc/nftables.conf
nft list ruleset
  1. 生产切换:
systemctl enable --now nftables
nft -f /etc/nftables.conf

确认 SSH/业务端口仍可用后,再清理旧 iptables 规则。

验证

回滚

常见坑

相关命令