V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
aboutboy
V2EX  ›  问与答

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

  •  
  •   aboutboy · 2022-03-04 08:24:36 +08:00 · 1143 次点击
    这是一个创建于 755 天前的主题,其中的信息可能已经有所发展或是发生改变。
    有台双网卡的 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 转发又不正常。

    因为对计算机网络和路由这块没怎么研究,希望能得到专业人士的指导。不胜感谢!
    5 条回复    2022-03-07 15:12:00 +08:00
    bg7lgb
        1
    bg7lgb  
       2022-03-04 08:46:46 +08:00
    去掉 MASQUERADE 规则 ,只保留两条 DNAT 试试
    bearice
        2
    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
        3
    360750581  
       2022-03-04 09:51:20 +08:00
    为啥一定要用 iptables ,换个思路,nginx 反代不是完美实现
    aboutboy
        4
    aboutboy  
    OP
       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
        5
    bearice  
       2022-03-07 15:12:00 +08:00
    @aboutboy gw => via 手误。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3241 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 12:15 · PVG 20:15 · LAX 05:15 · JFK 08:15
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.