搭建两台web服务器基于HAProxy实现负载均衡

image-20230302174007764

环境:

  • DNS服务器:192.168.10.200 仅主机模式
  • internet服务器:192.168.10.123 仅主机模式
  • web1:10.0.0.100 (安装apache2)NAT模式
  • web2:10.0.0.18 (安装httpd) NAT模式
  • HAProxy服务器:10.0.0.8(配备两块网卡,eth0NAT模式,属于内网;eth1 仅主机模式192.168.10.129,外网)
  1. 搭建DNS服务器
[root@dns ~]$ cat install_dns.sh 
#!/bin/bash
#
#***********************************************************
#Author:            yanli
#Date:              2022-10-25
#FileName:          install_dns.sh
#Description:        
#***********************************************************
DOMAIN=yanlinux.org
HOST=www
HOST_IP=192.168.10.129

CPUS=`lscpu |awk '/^CPU\(s\)/{print $2}'`
. /etc/os-release

color () {
    RES_COL=60
    MOVE_TO_COL="echo -en \\033[${RES_COL}G"
    SETCOLOR_SUCCESS="echo -en \\033[1;32m"
    SETCOLOR_FAILURE="echo -en \\033[1;31m"
    SETCOLOR_WARNING="echo -en \\033[1;33m"
    SETCOLOR_NORMAL="echo -en \E[0m"
    echo -n "$1" && $MOVE_TO_COL
    echo -n "["
    if [ $2 = "success" -o $2 = "0" ] ;then
        ${SETCOLOR_SUCCESS}
        echo -n $"  OK  "    
    elif [ $2 = "failure" -o $2 = "1"  ] ;then 
        ${SETCOLOR_FAILURE}
        echo -n $"FAILED"
    else
        ${SETCOLOR_WARNING}
        echo -n $"WARNING"
    fi
    ${SETCOLOR_NORMAL}
    echo -n "]"
    echo 
}


install_dns () {
    if [ $ID = 'centos' -o $ID = 'rocky' ];then
	    yum install -y  bind bind-utils
	elif [ $ID = 'ubuntu' ];then
        color "不支持Ubuntu操作系统,退出!" 1
        exit
	    #apt update
	    #apt install -y  bind9 bind9-utils
	else
	    color "不支持此操作系统,退出!" 1
	    exit
	fi
    
}

config_dns () {
    sed -i -e '/listen-on/s/127.0.0.1/localhost/' -e '/allow-query/s/localhost/any/' /etc/named.conf
    cat >> 	/etc/named.rfc1912.zones <<EOF
zone "$DOMAIN" IN {
    type master;
    file  "$DOMAIN.zone";
};
EOF
   cat > /var/named/$DOMAIN.zone <<EOF
\$TTL 1D
@	IN SOA	master admin (
					1	; serial
					1D	; refresh
					1H	; retry
					1W	; expire
					3H )	; minimum
	        NS	 master
master      A    `hostname -I`         
$HOST     	A    $HOST_IP
EOF
   chmod 640 /var/named/$DOMAIN.zone
   chgrp named /var/named/$DOMAIN.zone
}

start_service () {
    systemctl enable --now named
	systemctl is-active named.service
	if [ $? -eq 0 ] ;then 
        color "DNS 服务安装成功!" 0  
    else 
        color "DNS 服务安装失败!" 1
        exit 1
    fi   
}

install_dns
config_dns
start_service

#安装
[root@dns ~]$ sh install_dns.sh

#在internet服务器上测试
[root@internet ~]$ ping www.yanlinux.org
PING www.yanlinux.org (192.168.10.129) 56(84) bytes of data.
64 bytes from 192.168.10.129 (192.168.10.129): icmp_seq=1 ttl=64 time=0.358 ms
64 bytes from 192.168.10.129 (192.168.10.129): icmp_seq=2 ttl=64 time=0.475 ms
^C
--- www.yanlinux.org ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1008ms
rtt min/avg/max/mdev = 0.358/0.416/0.475/0.061 ms
  1. 搭建两台web服务器
#web1搭建
[root@web1 ~]$ apt -y install apache2
[root@web1 ~]$ cat /var/www/html/index.html
<h1>10.0.0.100 www.yanlinux.org</h1>

#web2搭建
[root@web2 ~]$ yum -y install httpd
[root@web2 ~]$ cat > /var/www/html/index.html
<h1>10.0.0.18 www.yanlinux.org</h1>
  1. 搭建HAProxy服务器
[root@haproxy ~]$ cat install_haproxy.sh 
#!/bin/bash

HAPROXY_VERSION=2.6.9
HAPROXY_FILE=haproxy-${HAPROXY_VERSION}.tar.gz
LUA_VERSION=5.4.4
LUA_FILE=lua-${LUA_VERSION}.tar.gz
HAPROXY_INSTALL_DIR=/apps/haproxy

SRC_DIR=/usr/local/src
CWD=`pwd`
CPUS=`lscpu|awk '/^CPU\(s\)/{print $2}'`
LOCAL_IP=$(hostname -I|awk '{print $1}')

STATS_AUTH_USER=admin
STATS_AUTH_PASSWD=123456

. /etc/os-release

color () {
    RES_COL=60
    MOVE_TO_COL="echo -en \\033[${RES_COL}G"
    SETCOLOR_SUCCESS="echo -en \\033[1;32m"
    SETCOLOR_FAILURE="echo -en \\033[1;31m"
    SETCOLOR_WARNING="echo -en \\033[1;33m"
    SETCOLOR_NORMAL="echo -en \E[0m"
    echo -n "$1" && $MOVE_TO_COL
    echo -n "["
    if [ $2 = "success" -o $2 = "0" ] ;then
        ${SETCOLOR_SUCCESS}
        echo -n $"  OK  "
    elif [ $2 = "failure" -o $2 = "1"  ] ;then
        ${SETCOLOR_FAILURE}
        echo -n $"FAILED"
    else
        ${SETCOLOR_WARNING}
        echo -n $"WARNING"
    fi
    ${SETCOLOR_NORMAL}
    echo -n "]"
    echo
}

check_file (){
    if [ ! -e ${HAPROXY_FILE} ];then
        color "请下载${HAPROXY_FILE}文件!" 1
        exit
    elif [ ! -e ${LUA_FILE} ];then
        color "请先下载${LUA_FILE}文件!" 1
        exit
    else
        color "相关文件已准备" 0
    fi
}

install_haproxy (){
    #安装依赖环境
    if [ $ID = "centos" -o $ID = "rocky" ];then
        yum -y install gcc make gcc-c++ glibc glibc-devel pcre pcre-devel openssl openssl-devel systemd-devel libtermcap-devel ncurses-devel libevent-devel readline-devel
    elif [ $ID = "ubuntu" ];then
        apt update
        apt -y install gcc make openssl libssl-dev libpcre3 libpcre3-dev zlib1g-dev  libreadline-dev libsystemd-dev
    else
        color "不支持此操作系统!" 1
        exit
    fi
    
    #安装lua环境
    tar xf ${LUA_FILE} -C ${SRC_DIR}
    LUA_DIR=${LUA_FILE%.tar*}  #变量高级用法,直接返回去掉.tar*的后缀
    cd ${SRC_DIR}/${LUA_DIR}
    make all test
    
    #编译安装haproxy
    cd ${CWD}
    tar xf ${HAPROXY_FILE} -C ${SRC_DIR}
    HAPROXY_DIR=${HAPROXY_FILE%.tar*}
    cd ${SRC_DIR}/${HAPROXY_DIR}
    make -j ${CPUS} ARCH=x86_64 TARGET=linux-glibc USE_PCRE=1 USE_OPENSSL=1 USE_ZLIB=1 USE_SYSTEMD=1 USE_CPU_AFFINITY=1 USE_LUA=1 LUA_INC=${SRC_DIR}/${LUA_DIR}/src/ LUA_LIB=${SRC_DIR}/${LUA_DIR}/src/ PREFIX=${HAPROXY_INSTALL_DIR}
    make install PREFIX=${HAPROXY_INSTALL_DIR}
    [ $? -eq 0 ] && color "HAProxy编译安装成功" 0 || { color "HAProxy编译安装失败,退出" 1;exit; }

    [ -L /usr/sbin/haproxy ] || ln -s ${HAPROXY_INSTALL_DIR}/sbin/haproxy /usr/sbin/ &> /dev/null
    [ -d /etc/haproxy ] || mkdir /etc/haproxy &> /dev/null
    [ -d /var/lib/haproxy/ ] || mkdir -p /var/lib/haproxy &> /dev/null

    #准备配置文件
    cat > /etc/haproxy/haproxy.cfg <<EOF
global
    maxconn 100000
    stats socket /var/lib/haproxy/haproxy.sock mode 600 level admin
    uid 99
    gid 99
    daemon

    pidfile /var/lib/haproxy/haproxy.pid
    log 127.0.0.1 local3 info

defaults
    option http-keep-alive
    option forwardfor
    maxconn 100000
    mode http
    timeout connect 300000ms
    timeout client 300000ms
    timeout server 300000ms

listen stats
    mode http
    bind 0.0.0.0:9999
    stats enable
    log global
    stats uri /haproxy-status
    stats auth ${STATS_AUTH_USER}:${STATS_AUTH_PASSWD}
EOF

    #创建用户
    groupadd -g 99 haproxy
    useradd -u 99 -g haproxy -d /var/lib/haproxy -M -r -s /sbin/nologin haproxy

    #创建service文件
    cat > /lib/systemd/system/haproxy.service <<EOF
[Unit]
Description=HAProxy Load Balancer
After=syslog.target network.target

[Service]
ExecStartPre=/usr/sbin/haproxy -f /etc/haproxy/haproxy.cfg -c -q
ExecStart=/usr/sbin/haproxy -Ws -f /etc/haproxy/haproxy.cfg -p /var/lib/haproxy/haproxy.pid
ExecReload=/bin/kill -USR2 $MAINPID

[Install]
WantedBy=multi-user.target
EOF

    systemctl daemon-reload
    systemctl enable --now haproxy
    systemctl is-active haproxy &> /dev/null && color "HAProxy安装完成" 0 || { color "HAProxy安装失败" 1;exit; }

    echo "-------------------------------------------------------------------"
    echo -e "请访问链接: \E[32;1mhttp://${LOCAL_IP}:9999/haproxy-status\E[0m"
    echo -e "用户和密码: \E[32;1m${STATS_AUTH_USER}/${STATS_AUTH_PASSWD}\E[0m"
}

main (){
    check_file
    install_haproxy
}

main

#安装haproxy
[root@haproxy ~]$ sh install_haproxy.sh

#配置proxies
[root@haproxy ~]$ vi /etc/haproxy/haproxy.cfg
#在文件最后加上下面几行信息
listen yanlinux_http_80
    bind 192.168.10.129:80
    mode http
    option forwardfor
    server web1 10.0.0.100:80 check inter 3000 fall 3 rise 5
    server web2 10.0.0.18:80 check inter 3000 fall 3 rise 5

#检查语法
[root@haproxy ~]$ haproxy -c -f /etc/haproxy/haproxy.cfg 
Configuration file is valid

#重启服务
[root@haproxy ~]$ systemctl restart haproxy.service 
#端口打开
[root@haproxy ~]$ ss -ntl 
State      Recv-Q     Send-Q            Local Address:Port           Peer Address:Port     Process     
LISTEN     0          128                     0.0.0.0:22                  0.0.0.0:*                    
LISTEN     0          128                     0.0.0.0:9999                0.0.0.0:*                    
LISTEN     0          128              192.168.10.129:80                  0.0.0.0:*                    
LISTEN     0          128                        [::]:22                     [::]:*
  1. internet服务器测试连接
[root@internet ~]$ curl www.yanlinux.org
<h1>10.0.0.100 www.yanlinux.org</h1>
[root@internet ~]$ curl www.yanlinux.org
<h1>10.0.0.18 www.yanlinux.org</h1>
  1. 健康性检测
#停掉web1的服务
[root@web1 ~]$ systemctl stop apache2.service


#internet测试,不会轮询到web1服务上了
[root@internet ~]$ curl www.yanlinux.org
<h1>10.0.0.18 www.yanlinux.org</h1>
[root@internet ~]$ curl www.yanlinux.org
<h1>10.0.0.18 www.yanlinux.org</h1>
[root@internet ~]$ curl www.yanlinux.org
<h1>10.0.0.18 www.yanlinux.org</h1>

状态页也可以看出来web1下线了

posted @ 2023-03-02 18:25  焱黎  阅读(77)  评论(5编辑  收藏  举报