Haproxy负载均衡原理(利用haproxy实现负载均衡)

后端服务有三个节点(node1、node2、node3),需要haproxy进行负载均衡,服务电器采用ubuntu操作系统。1.安装haproxy apt-get安装hapro。 ......

  后端服务有三个节点(node1,node2,node3),需要通过haproxy实现负载均衡,服务器具采用ubuntu操作系统。

  1、安装haproxy

  apt-get install haproxy

  2、修改配置文件

  vi /etc/haproxy/haproxy.cfg

  global

  log /dev/log local0

  log /dev/log local1 notice

  chroot /var/lib/haproxy

  stats socket /run/haproxy/admin.sock mode 660 level admin expose-fd listeners

  stats timeout 30s

  user haproxy

  group haproxy

  daemon

  # Default SSL material locations

  ca-base /etc/ssl/certs

  crt-base /etc/ssl/private

  # Default ciphers to use on SSL-enabled listening sockets.

  # For more information, see ciphers(1SSL). This list is from:

  # https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/

  # An alternative list with additional directives can be obtained from

  # https://mozilla.github.io/server-side-tls/ssl-config-generator/?server=haproxy

  ssl-default-bind-ciphers ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:RSA+AESGCM:RSA+AES:!aNULL:!MD5:!DSS

  ssl-default-bind-options no-sslv3

  defaults

  log global

  mode http

  option httplog

  option dontlognull

  timeout connect 5000

  timeout client 50000

  timeout server 50000

  errorfile 400 /etc/haproxy/errors/400.http

  errorfile 403 /etc/haproxy/errors/403.http

  errorfile 408 /etc/haproxy/errors/408.http

  errorfile 500 /etc/haproxy/errors/500.http

  errorfile 502 /etc/haproxy/errors/502.http

  errorfile 503 /etc/haproxy/errors/503.http

  errorfile 504 /etc/haproxy/errors/504.http

  listen stats

  bind 0.0.0.0:1080  

  stats refresh 30s 

  stats uri /stats 

  stats realm Haproxy Manager  

  stats auth admin:admin

  frontend main

  bind 0.0.0.0:80

  acl url_static path_beg -i /static /images /javascript /stylesheets

  acl url_static path_end -i .jpg .gif .png .css .js 

  default_backend webservice

  backend webservice

  balance leastconn

  server web1 node1:80 check

  server web2 node2:80 check

  server web3 node3:80 check

  3、加载配置文件使生效

  /usr/sbin/haproxy -f /etc/haproxy/haproxy.cfg

  配置说明:

  1、frontend main

  bind 0.0.0.0:80

  acl url_static path_beg -i /static /images /javascript /stylesheets

  acl url_static path_end -i .jpg .gif .png .css .js 

  default_backend webservice

  这里default_backend webservice需要和后端backend 保持一致

  2、backend webservice

  balance leastconn

  server web1 node1:80 check

  server web2 node2:80 check

  server web3 node3:80 check

  HAProxy还提供了其他类型的负载均衡:

  ?leastconn:每次将服务转发至连接数最少的服务器。

  ?source:对源IP地址进行哈希处理,用运行中服务器的总权重除以哈希值,即可决定哪台服务器将接收请求。

  ?uri:URI的左边部分(问号前面)经哈希处理,用运行中服务器的总权重除以哈希值。所得结果决定哪台服务器将接收请求。

  ?url_param:变量中指定的URL参数将在每个HTTP GET请求的查询串中进行查询。你基本上可以将使用蓄意制作的URL(crafted URL)的请求锁定于特定的负载均衡节点。

  ?hdr(name):HTTP头 将在每个HTTP请求中进行查询,被定向到特定节点。

  这里配置后端服务,端口可在具体每个server 上再用nginx做反向代理