方案一:iptables[支持TCP][支持UDP]
1、修改/etc/sysctl.conf 中 net.ipv4.ip_forward=1
2、sysctl -p
3、配置转发
iptables -t nat -A PREROUTING -p tcp --dport [端口号] -j DNAT --to-destination [目标IP]
iptables -t nat -A POSTROUTING -p tcp -d [目标IP] --dport [端口号] -j SNAT --to-source [本地服务器IP]
iptables -t nat -A PREROUTING -p udp --dport [端口号] -j DNAT --to-destination [目标IP]
iptables -t nat -A POSTROUTING -p udp -d [目标IP] --dport [端口号] -j SNAT --to-source [本地服务器IP]
4、重启生效
service iptables save
service iptables restart
方案二:haproxy[支持TCP][支持7层协议: http][负载均衡]
1、安装
yum install haproxy
apt install haproxy
2、配置转发
# vim /etc/haproxy/haproxy.cfg
global
log 127.0.0.1 local2
chroot /var/lib/haproxy
pidfile /var/run/haproxy.pid
maxconn 4000
user haproxy
group haproxy
daemon
# turn on stats unix socket
stats socket /var/lib/haproxy/stats
defaults
# 转发模式:tcp or http
# haproxy默认配置文件为http负载均衡的样例
# 这里介绍TCP转发模式
mode tcp
log global
option dontlognull
option http-server-close
option redispatch
retries 3
timeout http-request 10s
timeout queue 1m
timeout connect 10s
timeout client 1m
timeout server 1m
timeout http-keep-alive 10s
timeout check 10s
maxconn 3000
frontend mongo-in xxx.xxx.xxx.xxx:3717
default_backend mongo-out
backend mongo-out
balance roundrobin
server mongo1 xxx.xxx.xxx.xxx:3717 check
方案三:socat[支持TCP][支持UDP]
1、安装
yum install socat
apt install socat
2、配置转发
nohup socat LOCAL-TCP4-LISTEN:30000,reuseaddr,fork REMOTE-TCP4:1.1.1.1:30000 >> socat.log 2>&1 &
nohup socat -T 600 LOCAL-UDP4-LISTEN:10000,reuseaddr,fork REMOTE-UDP4:1.1.1.1:10000 >> socat.log 2>&1 &
说明:
实际端口方案还有多种,例如:rinetd,然而测试的时候rinetd经常性任务死掉。这里推荐使用iptables(更适用于NAT转发)和haproxy进行转发。