编译安装脚本如下
#!/bin/bash
#description: configure and install haproxy software
SOFTDIR=/usr/local/src
H_SOFT="haproxy-1.7.10.tar.gz"
H_SOFT_DIR="haproxy-1.7.10"
H_PREFIX="/usr/local/haproxy"
H_CONFIG_DIR="/etc/haproxy"
H_WORK_DIR="/var/lib/haproxy"
USER="haproxy"
GROUP="haproxy"
if ! id $USER &>/dev/null;then
groupadd -g 3320 -r $GROUP
useradd -u 3320 -g $GROUP -M -s /sbin/nologin $USER
fi
#install haproxy
cd $SOFTDIR && [ ! -f ${H_SOFT} ] && wget https://www.haproxy.org/download/1.7/src/${H_SOFT}
[ ! -d ${H_SOFT_DIR} ] && tar xf ${H_SOFT}
cd ${SOFTDIR}/${H_SOFT_DIR} && make TARGET=linux2628 ARCH=x86_64 PREFIX=${H_PREFIX} && make install PREFIX=${H_PREFIX}
if [ $? -ne 0 ];then
echo "install haproxy fail"
exit 1
fi
# create haproxy configure file
[ ! -d ${H_WORK_DIR} ] && mkdir -p ${H_WORK_DIR} && chown -R ${USER}.${GROUP} ${H_WORK_DIR}
[ ! -d ${H_CONFIG_DIR} ] && mkdir -p ${H_CONFIG_DIR}
cat > /etc/haproxy/haproxy.cfg <<EOF
global
log 127.0.0.1 local2
chroot ${H_WORK_DIR}
pidfile /var/run/haproxy.pid
maxconn 4000
user haproxy
group haproxy
daemon
stats socket ${H_WORK_DIR}/stats
defaults
mode http
log global
option httplog
option dontlognull
option http-server-close
option forwardfor except 127.0.0.0/8
option redispatch
option abortonclose
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 4000
listen stats
bind *:10800
mode http
option httplog
log 127.0.0.1 local3
stats refresh 30s
stats enable
stats uri /haproxyadmin?stats
stats realm Haproxy\ Statistics
stats auth Haproxyadmin:Aa123456
stats hide-version
stats admin if TRUE
frontend main
bind *:80
#acl url_static path_beg -i /static /images /javascript /stylesheets
#acl url_static path_end -i .jpg .gif .png .css .js
#use_backend static if url_static
default_backend webserver
#backend static
# balance roundrobin
# server static 127.0.0.1:4331 check
backend webserver
balance roundrobin
mode http
server web1 192.168.20.132:8082 check
server web2 192.168.20.133:8082 check
EOF
#copy haproxy start script
cd ${SOFTDIR}/${H_SOFT_DIR}
cp examples/haproxy.init /etc/init.d/haproxy
cd /etc/init.d/ && sed -i 's/\/usr\/sbin\/'\$BASENAME'/\/usr\/local\/haproxy\/sbin\/'\$BASENAME'/g' haproxy
chmod u+x /etc/init.d/haproxy
chkconfig --add haproxy
chkconfig haproxy on
if [ "`ss -tunlp|grep 80|awk -F '[ :]+' '{print $6}'`" = "80" ];then
echo "haproxy start fail,port 80"
exit 1
else
service haproxy start
fi
#configure log
sed -i 's/^#$ModLoad imudp/$ModLoad imudp/g' /etc/rsyslog.conf
sed -i 's/^#$UDPServerRun 514/$UDPServerRun 514/g' /etc/rsyslog.conf
echo "local2.* /var/log/haproxy.log" >> /etc/rsyslog.conf
echo "local3.* /var/log/haproxy_stats.log" >> /etc/rsyslog.conf
systemctl restart rsyslog