HAProxy 并不直接提供任何流量,这是后端服务器的工作,它们通常是网络或应用服务器。在这个练习中,我使用一个叫做 Ncat的工具,它是网络领域的“瑞士军刀”,用来创建一些极其简单的服务器。安装它:
$ sudo yum install nc -y
如果你的系统启用了 SELinux,你需要启用端口 8404,这是用于访问 HAProxy 统计页面的端口(下面有解释),以及你的后端服务器的端口:
$ sudo dnf install policycoreutils-python-utils$ sudo semanage port -a -t http_port_t -p tcp 8404$ sudo semanage port -a -t http_port_t -p tcp 10080$ sudo semanage port -a -t http_port_t -p tcp 10081$ sudo semanage port -a -t http_port_t -p tcp 10082
创建两个 Ncat 网络服务器和一个 API 服务器:
$ while true ;donc -l -p 10080 -c 'echo -e "HTTP/1.1 200 OK\n\n This is Server ONE"' ;done &$ while true ;donc -l -p 10081 -c 'echo -e "HTTP/1.1 200 OK\n\n This is Server TWO"' ;done &$ while true ;donc -l -p 10082 -c 'echo -e "HTTP/1.1 200 OK\nContent-Type: application/json\n\n { \"Message\" :\"Hello, World!\" }"' ;done &
这些简单的服务器打印出一条信息(如“This is Server ONE”),并运行到服务器停止为止。在现实环境中,你会使用实际的网络和应用程序服务器。
修改 HAProxy 的配置文件
HAProxy 的配置文件是 /etc/haproxy/haproxy.cfg。你在这里进行修改以定义你的负载平衡器。这个基本配置将让你从一个工作的服务器开始:
global log 127.0.0.1 local2 user haproxy group haproxydefaults mode http log global option httplogfrontend main bind *:80 default_backend web use_backend api if { path_beg -i /api/ } #------------------------- # SSL termination - HAProxy handles the encryption. # To use it, put your PEM file in /etc/haproxy/certs # then edit and uncomment the bind line (75) #------------------------- # bind *:443 ssl crt /etc/haproxy/certs/haproxy.pem ssl-min-ver TLSv1.2 # redirect scheme https if !{ ssl_fc }#-----------------------------# Enable stats at http://test.local:8404/stats#-----------------------------frontend stats bind *:8404 stats enable stats uri /stats#-----------------------------# round robin balancing between the various backends#-----------------------------backend web server web1 127.0.0.1:10080 check server web2 127.0.0.1:10081 check#-----------------------------# API backend for serving up API content#-----------------------------backend api server api1 127.0.0.1:10082 check
例如,当你对 /etc/haproxy/haproxy.cfg进行修改后,你需要用sudo systemctl reload haproxy来重新加载守护进程,使修改生效。如果有错误,它会让你知道,但继续用以前的配置运行。用sudo systemctl status haproxy检查 HAProxy 的状态。
如果它没有报告任何错误,你就有一个正在运行的服务器。在服务器上用 curl测试,在命令行输入curl http://localhost/。如果你看到 “This is Server ONE”,那就说明一切都成功了!运行curl几次,看着它在你的后端池中循环,然后看看当你输入curl http://localhost/api/时会发生什么。在 URL 的末尾添加/api/将把所有的流量发送到你池子里的第三个服务器。至此,你就有了一个正常运作的负载平衡器