系统学习 演练学习路径:35 个 lab 的难度排序、4 周基础计划与复盘方法

从 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 规则。

验证

回滚

常见坑

相关命令

参考链接

读完自测

合上页面,先回答,再展开对照。

  1. 迁移前应该导出哪些内容?
  2. 用什么工具把 iptables 规则翻译成 nftables?
  3. 生产切换前怎样验证 nftables 配置?
答案
  1. iptables-save/ip6tables-save 的规则和计数器、iptables 版本,以及 firewalld/ufw 的后端。
  2. iptables-translate;翻译后仍要人工核对语义。
  3. 测试机用 nft -c -f 校验,再 nft -f 加载并用 nft list ruleset 核对,确认 SSH/业务端口可用后再清理旧规则。
微信小程序码:扫码打开命令速查小程序

小程序版

微信扫码,随时查命令