不建议直接用nftables硬切换iptables,应分步迁移:先建ip协议族表链结构,再用iptables-restore-translate迁移规则并测试,最后停用iptables服务、启用nftables持久化并验证回滚。

直接用 nftables 替代 iptables 不建议“硬切换”,尤其在运行中的老旧服务器上。关键不是删掉旧规则,而是分步迁移、验证、持久化,确保网络不中断。核心思路是:先建表链结构、再复用已有逻辑、最后停用 iptables 工具链。
创建兼容性高的默认表结构
老旧服务器通常只处理 IPv4 流量,推荐用 ip 协议族而非 inet(后者需同时兼容 IPv6,可能引入意外行为)。执行以下命令一次性搭好基础框架:
-
新建 filter 表:
nft add table ip filter -
添加 input 链(默认丢弃):
nft add chain ip filter input { type filter hook input priority 0 \; policy drop \; } -
添加 output 链(默认放行):
nft add chain ip filter output { type filter hook output priority 0 \; policy accept \; } -
添加 forward 链(默认丢弃,如非网关可跳过):
nft add chain ip filter forward { type filter hook forward priority 0 \; policy drop \; }
把现有 iptables 规则安全迁移到 nftables
不要手动重写——利用系统自带转换工具,保留语义一致性:
- 先备份原规则:
iptables-save > /root/iptables-backup.v4 - 生成 nftables 格式:
iptables-save | iptables-restore-translate -o /tmp/migrated.nft - 检查输出内容是否合理(比如 SSH、ICMP、已建立连接等关键规则是否都在)
- 加载测试:
nft -f /tmp/migrated.nft,确认服务仍可达
若转换后有异常(如某些端口不通),可临时加一条兜底规则:nft add rule ip filter input counter accept,再逐条排查原规则对应项。
停用 iptables 工具链,启用 nftables 持久化
确保系统重启后自动加载,且 iptables 命令不再干扰:
- 保存当前规则为系统配置:
nft list ruleset > /etc/nftables.conf - 禁用 iptables 服务(Debian/Ubuntu):
systemctl stop iptables && systemctl disable iptables - 启用 nftables 服务:
systemctl enable nftables && systemctl start nftables - 验证开机自启是否生效:
systemctl is-enabled nftables应返回 enabled
注意:部分发行版(如 RHEL 8+)默认已用 nftables 后端支撑 firewalld,此时不应直接禁用 iptables 服务,而应通过 firewall-cmd 管理,或切换 firewalld 后端为 nftables 模式。
验证与回滚准备
迁移完成后必须做三件事:
- 用
nft list ruleset对照原iptables -L -n -v,确认关键策略(如 SSH、DNS、NTP)未丢失 - 从外部 ping + telnet 测试常用端口,确保无静默丢包
- 保留一份可一键回滚的脚本(例如还原 iptables-save 备份 + 重启 netfilter 服务)
老旧服务器往往承担关键业务,平滑替代的核心是“先共存、再替换、最后清理”,而不是追求一步到位。

















