配置文件位置: /etc/haproxy/haproxy.cfg
关键点: Reqrep 正则重写URL
解决的问题场景: 负载均衡机器出口端口统一为80,代理后台API,Docs,Websocket,Web页面四个服务,服务端口不一。
最终实现结果:
10.0.0.3/api --> 10.0.0.1:8080 --> API服务 10.0.0.3 --> 10.0.0.2:8080 --> Web页面 10.0.0.3/ws --> 10.0.0.1:8443 --> Websocket服务 10.0.0.3/docs --> 10.0.0.2:9000 --> Docs文档
配置详情:
1 Frontend App *:80 2 acl uri_api path_beg /api/ 3 acl uri_web path_beg / 4 acl uri_docs path_beg /docs/ 5 acl uri_socket hdr(Upgrade) -i Websocket 6 acl uri_socket hdr_beg(Host) -i ws 7 8 Use_backend api if uri_api 9 Use_backend socket if uri_socket 10 Use_backend web if uri_web 11 Use_backend docs if uri_docs 12
13 Backend api
14 balance roundrobin 15 reqrep ^([^ ]* /)api[/]?(*) 12 16 server server1 10.0.0.1:8080 check 17 18 Backend socket 19 balance roundrobin 20 timeout queue 1h 21 timeout server 1h 22 timeout connect 1h 23 server server1 10.0.0.1:8443 check 24 25 Backend web 26 balance roundrobin 27 server server1 10.0.0.2:8080 check 28 29 Backend docs 30 balance roundrobin 31 server server1 10.0.0.2:9000 check