Centos7安装HAProxy反向代理,TCP 4、7层反向代理和负载均衡,常用作数据库负载均衡

本教程用做数据库负载均衡

命令安装haproxy v1.8.0

安装教程

yum -y install gcc gcc-c++ make wget
wget https://github.com/haproxy/haproxy/archive/v1.8.0.tar.gz
tar zxf v1.8.0.tar.gz
cd haproxy-1.8.0
make TARGET=linux2628 PREFIX=/usr/local/haproxy
make install PREFIX=/usr/local/haproxy
# 其他配置
cp /usr/local/haproxy/sbin/haproxy /usr/sbin/
cp ./examples/haproxy.init /etc/init.d/haproxy 
chmod 755 /etc/init.d/haproxy
# 创建用户
useradd -r haproxy
# 创建配置文件
mkdir /etc/haproxy
vim /etc/haproxy/haproxy.cfg

配置文件示例

# 全局配置参数
global
    log 127.0.0.1 local0 notice
    chroot /usr/local/haproxy
    user haproxy
    group haproxy
    #守护进程启动
    daemon

# 一些默认参数
defaults
    log global
    retries 3
    option  dontlognull
    option redispatch
    timeout connect 5000
    timeout server 5000
    timeout client 5000
    #最大连接数
    maxconn 5000

# 这个是我们定义的负载均衡的配置
listen mysql-lb1
    # 绑定的IP和端口 haproxy服务器一个网卡IP
    bind *:4444
    # 模式是TCP
    mode tcp
    # 负载均衡算法是 轮询
    balance roundrobin
    # 下面两个就是后端被访问的server
    server mysql_1 192.168.226.136:4000 weight 1 check

# 自带的监控服务器的配置
# 监控服务的端口是 8888
listen stats
       bind *:8888
       # 监控模式是http
       mode http
       option httpclose
       balance roundrobin
       stats uri /
       stats realm Haproxy\ Statistics
       # 监控的用户名和密码
       stats auth myadmin:myadmin

启动

service haproxy start

QQ截图20181012214711.jpg

Docker安装haproxy v2.4.4

镜像地址

https://hub.docker.com/_/haproxy

安装教程

docker run -d -p 8888:8888 -p 4444:4444 -v /data/haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg haproxy:2.4.4

配置文件示例

# 一些默认参数
defaults
    mode            tcp
    log             global
    option          tcplog
    option          dontlognull
    option http-server-close
    option          redispatch
    retries         3
    timeout http-request 10s
    timeout queue   1m
    timeout connect 10s
    timeout client  1m
    timeout server  1m
    timeout http-keep-alive 10s
    timeout check   10s
    #最大连接数
    maxconn 5000

# 这个是我们定义的负载均衡的配置
listen test
    # 绑定的IP和端口 haproxy服务器一个网卡IP
    bind *:4444
    # 模式是TCP
    mode tcp
    # 负载均衡算法是 轮询
    balance roundrobin
    # 下面两个就是后端被访问的server
    server test 192.168.3.37:30000 weight 1 check

# 自带的监控服务器的配置
# 监控服务的端口是 8888
listen stats
       bind *:8888
       # 监控模式是http
       mode http
       option httpclose
       balance roundrobin
       stats   enable
       stats   hide-version
       stats uri /
       stats realm Haproxy\ Statistics
       # 监控的用户名和密码
       stats auth admin:admin
       stats admin if TRUE

微信截图_20210920163810.png