关于 Linux 双外网网卡实现 nat 端口转发遇到的问题

2022-03-04 08:24:36 +08:00
 aboutboy
有台双网卡的 centos 。
eth0 的外网 IP 为:35.68.21.210 ,内网 IP 为:172.31.11.120 ; eth1 的外网 IP 为:3.112.105.71 ,内网 IP 为:172.31.6.9 。网关都是 172.31.0.1 (慎重考虑起见,真实外网 IP 不是所写的)

现在需要实现的是:将访问 eth0 和 eth1 的 80 端口流量都转发到后端一台服务器的 80 端口。
采用 iptables 实现:
iptables -t nat -A PREROUTING -p tcp --dport 80 -j DNAT --to-destination 后端 IP
iptables -t nat -A POSTROUTING -p tcp --dport 80 -j MASQUERADE
默认路由是 eth0
在执行上述操作后,eth0 转发是正常的,访问 http://35.68.21.210 ,可以得到正常的返回。
但 eth1 不能转发。(感觉是路由的原因)

当前路由表如下:
[root@ip-172-31-11-120 ~]# route
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
default ip-172-31-0-1.a 0.0.0.0 UG 0 0 0 eth0
172.31.0.0 0.0.0.0 255.255.240.0 U 0 0 0 eth0
172.31.0.0 0.0.0.0 255.255.240.0 U 0 0 0 eth1

将默认路由设置为 eth1:
route add default gw 172.31.0.1 dev eth1
执行后,eth1 转发是正常的,但 eth0 转发又不正常。

因为对计算机网络和路由这块没怎么研究,希望能得到专业人士的指导。不胜感谢!
1191 次点击
所在节点    问与答
5 条回复
bg7lgb
2022-03-04 08:46:46 +08:00
去掉 MASQUERADE 规则 ,只保留两条 DNAT 试试
bearice
2022-03-04 09:06:45 +08:00
默认路由的问题,用策略路由指定 eth1 的 IP 走另一个路由表就行了
ip rule add from 3.112.105.71 lookup 100
ip route add default gw 172.31.0.1 dev eth1 table 100
360750581
2022-03-04 09:51:20 +08:00
为啥一定要用 iptables ,换个思路,nginx 反代不是完美实现
aboutboy
2022-03-06 21:13:30 +08:00
@bearice 感觉你这个方法是正确的思路。
不过我在执行 ip route add default gw 172.31.0.1 dev eth1 table 100 时,提示错误:
Error: either "to" is duplicate, or "gw" is a garbage.
现在还是不能实现两张网卡同时 nat
bearice
2022-03-07 15:12:00 +08:00
@aboutboy gw => via 手误。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/837836

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX