IP 转发在 Ubuntu 系统中不生效解决方法

问题:

在 Ubuntu 22.04 中使用多种方法设置 IP Forwarding 不能即时生效,需要重启。

尝试了修改 /etc/sysctl.conf 和 使用 sysctl 指令修改 net.ipv4.ip_forward 参数,发现 IP forwarding 功能不正常,需要重启后才能生效,但 ip_forward 文件显示功能已经打开。

1
2
$cat /proc/sys/net/ipv4/ip_forward
1

重启后若 ip_forward 开机状态为 1 时,随意修改该参数可以生效。

解决方案:

经过排查,发现是 iptables 防火墙规则没有允许。

1
2
3
4
5
6
7
8
9
10
11
> sudo iptables -L
Chain INPUT (policy ACCEPT)
target prot opt source destination

Chain FORWARD (policy DROP)
target prot opt source destination
ACCEPT all -- anywhere anywhere ctstate RELATED,ESTABLISHED
DOCKER all -- anywhere anywhere
ACCEPT all -- anywhere anywhere
ACCEPT all -- anywhere anywhere
......

可以使用 iptables -P FORWARD ACCEPT 允许转发策略。