VPS上使用haproxy和iptables进行代理中转与端口转发

VPS上使用haproxy和iptables进行代理中转与端口转发

haproxy iptables VPS Posted by crackfree on August 24, 2017
## 前言 --- 因为A VPS上装了锐速,另B VPS上配置了代理。A的链路好,而A上配置代理有坑。因此想办法把两者的有点结合起来,做一个端口转发将A的端口转发至B,来提升代理的速度。 此时网络连接链路变为: Me <--> A<-->B<--> Internet 现在有两种方案: - haproxy - iptables haproxy: 优点:效率高 缺点:配置比第二种复杂 iptables: 优点:配置简单,不用装软件 缺点:效率不如第一种高 ## haproxy配置方法 ### haproxy 介绍 > HAProxy is a free, very fast and reliable solution offering high availability, load balancing, and proxying for TCP and HTTP-based applications. It is particularly suited for very high traffic web sites and powers quite a number of the world's most visited ones. Over the years it has become the de-facto standard opensource load balancer, is now shipped with most mainstream Linux distributions, and is often deployed by default in cloud platforms. Since it does not advertise itself, we only know it's used when the admins report it :-) ![](http://www.haproxy.org/img/haproxy-pmode.png) [项目官网](http://www.haproxy.org/) PS:这么强悍的软件用来当中转有点浪费。 安装 yum install haproxy vim /etc/haproxy/haproxy.cfg 将配置文件替换如下: global ulimit-n 51200 defaults log global mode tcp option dontlognull contimeout 1000 clitimeout 150000 srvtimeout 150000 #上面這一塊內容即將失效,需要更換為 #timeout connect 1000 #timeout client 150000 #timeout server 150000 frontend ss-in bind *:8388 default_backend ss-out backend ss-out server server1 US_VPS_IP:8388 maxconn 20480 将backend ss-out下面US_VPS_IP 改为要转发到的远程IP和端口,将frontend ss-in下面 bind *:8388改为本地要监听的端口 - 启动与开机启动haproxy service haproxy start systemctl enable haproxy 此时是以root身份启动,想以nobody身份运行。将下面保存为/root/haproxy.sh,后将文件加入/etc/rc.local作为开机启动。 #! /bin/bash ulimit-n 51200 sudo -u nobody haproxy /etc/haproxy/haproxy.cfg 如果你想进一步折腾haproxy可以参考 - [http://linux.die.net/man/1/haproxy](http://linux.die.net/man/1/haproxy)。 - [http://www.linuxidc.com/wap.aspx?nid=118968](http://www.linuxidc.com/wap.aspx?nid=118968) ## iptables配置 --- vim /etc/sysctl.conf 添加: net.ipv4.ip_forward=1 sysctl -p /etc/sysctl.conf A 88端口 -> B:8888端口: iptables -t nat -A PREROUTING -d A -p tcp --dport 88 -j DNAT --to-destination B:8888 将发到8888端口的包,IP伪装成A iptables -t nat -A POSTROUTING -d B -p tcp --dport 8888 -j SNAT --to A ## 总结 --- haproxy和iptables不仅可以用于前言中的转发用途,还可以用做国内VPS到国外VPS的中转来提升速度