环境:阿里云ECS专用网络
主机A 公网IP:1.1.1.1 私网:192.168.0.1 。主机B:无公网IP,私网IP:192.168.0.2
需求:主机B提供了mysql服务。需要公网能访问。
方法一: 最简单的配置方法,在主机A上执行即可。端口一致的情况
[root@linuxso.com ~]#iptables -t nat -I PREROUTING -p tcp --dport 3306 -j DNAT --to 192.168.0.2
[root@linuxso.com ~]#iptables -t nat -I POSTROUTING -p tcp --dport 3306 -j MASQUERADE
[root@linuxso.com ~]#service iptables save //保存
方法二:端口不一致,比如访问公网IP的8888端口指向主机B的3306端口
[root@linuxso.com ~]#iptables -t nat -A PREROUTING -d 192.168.0.1 -p tcp --dport 8888 -j DNAT --to-destination 192.168.0.2:3306
[root@linuxso.com ~]#iptables -t nat -A POSTROUTING -s 0.0.0.0/0 -p tcp --dport 3306 -j SNAT --to-source 192.168.0.1
[root@linuxso.com ~]#iptables -t nat -A PREROUTING -d 1.1.1.1 -p tcp --dport 8888 -j DNAT --to-destination 192.168.0.2:3306
[root@linuxso.com ~]#iptables -t nat -A POSTROUTING -s 0.0.0.0/0 -p tcp --dport 3306 -j SNAT --to-source 1.1.1.1
[root@linuxso.com ~]#service iptables save //保存