haproxy简单使用(一)

haproxy的安装

[root@haproxy ~]# yum install haproxy -y
已加载插件:fastestmirror
Determining fastest mirrors
epel/x86_64/metalink                                                                                          | 8.9 kB  00:00:00     
 * base: mirrors.aliyun.com
 * epel: mirrors.ustc.edu.cn
 * extras: mirrors.aliyun.com
 * updates: mirrors.aliyun.com
base                                                                                                          | 3.6 kB  00:00:00     
epel                                                                                                          | 4.7 kB  00:00:00     
extras                                                                                                        | 3.4 kB  00:00:00     
updates                                                                                                       | 3.4 kB  00:00:00     
(1/4): extras/7/x86_64/primary_db                                                                             | 156 kB  00:00:00     
(2/4): updates/7/x86_64/primary_db                                                                            | 2.4 MB  00:00:00     
(3/4): epel/x86_64/primary_db                                                                                 | 6.6 MB  00:00:01     
(4/4): epel/x86_64/updateinfo                                                                                 | 959 kB  00:00:01     
正在解决依赖关系
--> 正在检查事务
---> 软件包 haproxy.x86_64.0.1.5.18-8.el7 将被 安装
--> 解决依赖关系完成

依赖关系解决

=====================================================================================================================================
 Package                        架构                          版本                                 源                           大小
=====================================================================================================================================
正在安装:
 haproxy                        x86_64                        1.5.18-8.el7                         base                        834 k

事务概要
=====================================================================================================================================
安装  1 软件包

总下载量:834 k
安装大小:2.6 M
Downloading packages:
haproxy-1.5.18-8.el7.x86_64.rpm                                                                               | 834 kB  00:00:00     
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  正在安装    : haproxy-1.5.18-8.el7.x86_64                                                                                      1/1 
  验证中      : haproxy-1.5.18-8.el7.x86_64                                                                                      1/1 

已安装:
  haproxy.x86_64 0:1.5.18-8.el7                                                                                                      

完毕!

haproxy相关的文件:

[root@haproxy ~]# rpm -ql haproxy
/etc/haproxy                # 主配置目录
/etc/haproxy/haproxy.cfg    # 主配置文件
/etc/logrotate.d/haproxy    # 日志滚动
/etc/sysconfig/haproxy        # 启动参数
/usr/bin/halog
/usr/bin/iprange
/usr/lib/systemd/system/haproxy.service    # 服务脚本
/usr/sbin/haproxy
/usr/sbin/haproxy-systemd-wrapper
/usr/share/doc/haproxy-1.5.18
......
/usr/share/doc/haproxy-1.5.18/examples    # 样例配置目录,下面都是一些特定样例
/usr/share/doc/haproxy-1.5.18/examples/acl-content-sw.cfg
/usr/share/doc/haproxy-1.5.18/examples/auth.cfg
/usr/share/doc/haproxy-1.5.18/examples/build.cfg
/usr/share/doc/haproxy-1.5.18/examples/content-sw-sample.cfg
/usr/share/doc/haproxy-1.5.18/examples/cttproxy-src.cfg
/usr/share/doc/haproxy-1.5.18/examples/examples.cfg
/usr/share/doc/haproxy-1.5.18/examples/haproxy.cfg
/usr/share/doc/haproxy-1.5.18/examples/option-http_proxy.cfg
/usr/share/doc/haproxy-1.5.18/examples/ssl.cfg
/usr/share/doc/haproxy-1.5.18/examples/tarpit.cfg
/usr/share/doc/haproxy-1.5.18/examples/test-section-kw.cfg
/usr/share/doc/haproxy-1.5.18/examples/transparent_proxy.cfg
/usr/share/doc/haproxy-1.5.18/examples/url-switching.cfg
......
/usr/share/haproxy
/usr/share/haproxy/400.http        # 主要的几个状态页面
/usr/share/haproxy/403.http
/usr/share/haproxy/408.http
/usr/share/haproxy/500.http
/usr/share/haproxy/502.http
/usr/share/haproxy/503.http
/usr/share/haproxy/504.http
/usr/share/haproxy/README
/usr/share/man/man1/halog.1.gz    # 帮助文档类
/usr/share/man/man1/haproxy.1.gz
/var/lib/haproxy           # haproxy数据库位置

快速使用案例

#备份主配置文件
[root@haproxy ~]# cd /etc/haproxy/
[root@haproxy haproxy]# ls
haproxy.cfg
[root@haproxy haproxy]# cp haproxy.cfg{,_bak20190211}
[root@haproxy haproxy]# ll
总用量 8
-rw-r--r-- 1 root root 3142 10月 30 22:46 haproxy.cfg
-rw-r--r-- 1 root root 3142 2月  11 11:08 haproxy.cfg_bak20190211

# 删除这行(main frontend which proxys to the backends)后面的所有行
[root@haproxy haproxy]# vim haproxy.cfg
# 添加下面几行
frontend web *:80
        default_backend webservers

backend webservers
        balance roundrobin
        server ng1 10.0.3.80:80 check
        server ng2 10.0.3.81:80 check

# 准备后端的web服务
[root@ng1 ~]# wget https://raw.githubusercontent.com/uscwifi/yum-repository/master/nginx-centos7.repo -O /etc/yum.repos.d/nginx-centos7.repo
[root@ng1 ~]# yum install nginx -y
[root@ng1 ~]# hostnamectl > /usr/share/nginx/html/index.html

[root@ng2 ~]# wget https://raw.githubusercontent.com/uscwifi/yum-repository/master/nginx-centos7.repo -O /etc/yum.repos.d/nginx-centos7.repo
[root@ng2 ~]# yum install nginx -y
[root@ng2 ~]# hostnamectl > /usr/share/nginx/html/index.html

# 测试
[root@haproxy haproxy]# systemctl restart haproxy
[root@haproxy haproxy]# curl 10.0.3.65
   Static hostname: ng1
         Icon name: computer-vm
           Chassis: vm
        Machine ID: b0f0ac8243284617b4f0f71d120c1d9b
           Boot ID: a0111a864dad4341ad1a59eb27698b4d
    Virtualization: vmware
  Operating System: CentOS Linux 7 (Core)
       CPE OS Name: cpe:/o:centos:centos:7
            Kernel: Linux 3.10.0-862.14.4.el7.x86_64
      Architecture: x86-64
[root@haproxy haproxy]# curl 10.0.3.65
   Static hostname: ng2
         Icon name: computer-vm
           Chassis: vm
        Machine ID: b0f0ac8243284617b4f0f71d120c1d9b
           Boot ID: a8210a85b94b4752bfe7161438d1604e
    Virtualization: vmware
  Operating System: CentOS Linux 7 (Core)
       CPE OS Name: cpe:/o:centos:centos:7
            Kernel: Linux 3.10.0-862.14.4.el7.x86_64
      Architecture: x86-64

日志配置

在haproxy的配置文件中,默认已经绑定到local2上了,我们需要在rsyslog上关联下。

# 修改/var/log/haproxy.log
[root@haproxy ~]# vim /etc/sysconfig/rsyslog
SYSLOGD_OPTIONS="-r"

# 修改/etc/rsyslog.conf
[root@haproxy ~]# vim /etc/rsyslog.conf# 解开如下4行注释内容
# Provides UDP syslog reception
$ModLoad imudp
$UDPServerRun 514

# Provides TCP syslog reception
$ModLoad imtcp
$InputTCPServerRun 514

# 添加如下行
local2.*                                                /var/log/haproxy.log

# 重启下服务
[root@haproxy ~]# systemctl daemon-reload 
[root@haproxy ~]# systemctl restart rsyslog.service 
[root@haproxy ~]# systemctl restart haproxy.service

# 请求一次
[root@haproxy ~]# !curl
curl 10.0.3.65
   Static hostname: ng1
         Icon name: computer-vm
           Chassis: vm
        Machine ID: b0f0ac8243284617b4f0f71d120c1d9b
           Boot ID: a0111a864dad4341ad1a59eb27698b4d
    Virtualization: vmware
  Operating System: CentOS Linux 7 (Core)
       CPE OS Name: cpe:/o:centos:centos:7
            Kernel: Linux 3.10.0-862.14.4.el7.x86_64
      Architecture: x86-64

# 查看日志
[root@haproxy ~]# tail /var/log/haproxy.log 
Feb 11 11:43:03 localhost haproxy[2179]: Proxy web started.
Feb 11 11:43:03 localhost haproxy[2179]: Proxy webservers started.
Feb 11 11:44:06 localhost haproxy[2180]: 10.0.3.65:58878 [11/Feb/2019:11:44:06.142] web webservers/ng1 0/0/60/1/61 200 610 - - ---- 1/1/0/0/0 0/0 "GET / HTTP/1.1"

主要配置参数

global配置项:

    chroot: 切换根运行目录
    uid,gid: 运行用户和组
    user,group:运行用户和组
    daemon: 是否守护进程
    log:     配置日志和相应的级别
    nbproc:  要启动的haproxy的进程数量
    ulimit:  每个haproxy进程可打开的最大文件数量

    maxconn: 设定每个haproxy进程能接受的最大并发连接数量
    maxconnrate: 每个进程每秒能创建的最大连接数量
    maxsslconn: 每个haproxy进程所能接受的ssl最大并发连接数量
    spread-checks: 散开检查工作

代理配置项:

    defaults: 默认的
    frontend: 前段
    backend: 后端的
    listen: 监听

    bind: 绑定地址和端口
    balance: 指定调度算法类型和算法参数
            roundrobin: 轮调
            static-rr: 静态轮调
            leastconn: 最小连接
            first: 前面的达到上限在调度下一个
            source: 源地址hash
            uri: 对uri左半部分做hash计算,派发到下面服务器
            url_param: 对参数做hash计算,然后派发
            hdr: 对特定的http首部做hash计算

    hash-type: hash类型,map-based,consistent
    default_backend: 默认后端
    default_server: 默认服务器
        name: 名字
        address: 地址
        port: 端口
        maxconn:最大连接
        backlog: 后援队列长度
        check 健康检查
            addr: 检查地址
            port: 检查端口
            inter: 检查间隔
            rise: 多少次检查成功认为可用
            fall: 多少次失败标记不可用
        cookie: 设置cookie值
        disabled: 标记不可用
        on-error: 后端服务故障时候的行动策略

统计接口相关参数
    states enable ,启动后可以通过ip/haproxy?stats访问
        stats uri : /haproxy?stats
        stats realm: "认证提示"
        stats refresh: 设定自动刷新时间间隔
        stats admin: 启用stats page的管理功能
    配置样例:
        listen stats
            bind :9090
            stats enable
            stats realm " stat page"
            stats auth admin:admin
            stats admin if TRUE


mode: 工作模式,支持tcp,http,health三种

option forwardfor [except network] :  添加forwardfor信息
erroffile <code> <file>: 错误文件
errorloc302  <code> <url>: 指定一个url地址
reqadd: 请求头添加
rspdel: 响应头删除
rspadd: 响应头添加
option httpchk  uri: 特定uri的http检查
use_backend <backup>:使用特定后端
default_backend:默认后端
http-request {allow,deny} {if 条件}: 如果特定条件就执行特定动作
http_request set-header X-Forwarded-Port %{dst_port}

压缩功能
    compression algo: 指定http压缩了下
    compression type:对特定类型压缩

连接超时相关
    timout client : 客户端超时
    timeout server: 客户端超时
    timeout http-request: 请求的超时时长
    timeout connect: 连接超时时长
    timout client-fin  等待fin的时间
    timeout server-find 等待fin的时间

acl设置
    acl invalid_src src ip : 设置一个命名的acl
    block if invalid_src: 如果特定条件满足就403返回

常用配置

1.后台记录真实的客户端ip方法

  • 默认default已经有forwardfor配置了。 可以在后端的服务器上面使用X-Forwarded-For头来记录真实的客户端地址。 可以使用命令 “tcpdump -i ens33 port 80 -nn -vv” 去抓取调度到后端的服务器的请求头信息, 这里有一个样例的信息(部分的):

10.0.3.65.51874 > 10.0.3.81.80: Flags [P.], cksum 0x1b30 (incorrect -> 0x2879), seq 1:121, ack 1, win 229, options [nop,nop,TS val 12953886 ecr 12949091], length 120: HTTP, length: 120
	GET / HTTP/1.1
	User-Agent: curl/7.29.0
	Host: 10.0.3.65
	Accept: */*
	X-Forwarded-For: 10.0.3.64
	Connection: close

剩下的就是在web的日志格式中添加该变量即可。

动静分离

frontend web *:80
        acl url_static path_beg -i /static  /images/  /javascript /stylesheets /css /js
        acl url_static path_end -i .jpg .gif .png .css .js .html .txt .htm
        use_backend staticsrvs if url_static
        default_backend webservers

backend webservers
        balance roundrobin
        cookie BACKENDSRV insert nocache indirect
        server ng1 10.0.3.80:80 cookie ng1 check inter 2000 rise 2 fall 5 weight 20
backend staticsrvs
        balance roundrobin
        server ng1 10.0.3.80:80 cookie ng1 check inter 2000 rise 2 fall 5 weight 20
        server ng2 10.0.3.81:80 cookie ng2 check inter 2000 rise 2 fall 5 weight 20

# 后端的80 机器需要构建一个php页面,安装php-fpm包,主要配置如下

[root@ng1 ~]# systemctl start php70-php-fpm.service
[root@ng1 ~]# ss -ltn | grep :9000
LISTEN     0      128    127.0.0.1:9000                     *:*    
[root@ng1 ~]# vim /etc/nginx/conf.d/default.conf 
    location ~ \.php$ {
        root           html;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        #fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }
[root@ng1 ~]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@ng1 ~]# nginx -s reload

# php主页设置
[root@ng1 ~]# vim /usr/share/nginx/html/index.php
<?php
echo "今天是 " . date("Y/m/d") . "<br>";
echo "\n"
?>

# 访问测试
[root@client ~]# for i in {1..10};do curl 10.0.3.65/index.php;curl 10.0.3.65/index.html;done
今天是 2019/02/12<br>
ng1
今天是 2019/02/12<br>
ng2
今天是 2019/02/12<br>
ng1
今天是 2019/02/12<br>
ng2
今天是 2019/02/12<br>
ng1
今天是 2019/02/12<br>
ng2
今天是 2019/02/12<br>
ng1
今天是 2019/02/12<br>
ng2
今天是 2019/02/12<br>
ng1
今天是 2019/02/12<br>
ng2

配置支持https协议

# 准备证书
[root@haproxy ~]# cd /etc/ssl/certs/
[root@haproxy certs]# make jd.crt
[root@haproxy certs]# openssl rsa -in jd.key -out jd.key2   #去掉私钥密码

#这里要注意hapeoxy使用的证书是crt和key合起来的证书
[root@haproxy certs]# cat jd.crt jd.key2 > jd.pem

# 配置haproxy
frontend web 
        bind *:443 ssl crt /etc/ssl/cert/jd.pem
        bind *:80
        redirect scheme https if !{ ssl_fc }


        acl url_static path_beg -i /static  /images/  /javascript /stylesheets /css /js
        acl url_static path_end -i .jpg .gif .png .css .js .html .txt .htm
        use_backend staticsrvs if url_static
        default_backend webservers

backend webservers
        balance roundrobin
        cookie BACKENDSRV insert nocache indirect
        server ng1 10.0.3.80:80 cookie ng1 check inter 2000 rise 2 fall 5 weight 20
backend staticsrvs
        balance roundrobin
        server ng1 10.0.3.80:80 cookie ng1 check inter 2000 rise 2 fall 5 weight 20
        server ng2 10.0.3.81:80 cookie ng2 check inter 2000 rise 2 fall 5 weight 20
[root@haproxy certs]# systemctl restart haproxy.service

访问测试:
[root@client ~]# curl  https://10.0.3.65 -k
今天是 2019/02/13<br>
[root@client ~]# curl  https://10.0.3.65 -k
今天是 2019/02/13<br>
[root@client ~]# curl  https://10.0.3.65 -k
今天是 2019/02/13<br>
[root@client ~]# curl  https://10.0.3.65/index.html -k
ng1
[root@client ~]# curl  https://10.0.3.65/index.html -k
ng2

猜你喜欢

转载自blog.csdn.net/qq_33317586/article/details/86982975