haproxy 負(fù)載均衡&配置http+https負(fù)載集群實戰(zhàn)
haproxy負(fù)載均衡
一、簡介
HAProxy是一種開源的負(fù)載均衡和代理服務(wù)器軟件,可以實現(xiàn)高可用性和性能優(yōu)化。它通常用于將傳入的請求分發(fā)到多個后端服務(wù)器,以達到負(fù)載均衡的目的。
Haproxy 是一個使用C語言編寫的自由及開放源代碼軟件,其提供高可用性、負(fù)載均衡,以及基于TCP和HTTP的應(yīng)用程序代理。
HAProxy是一個免費的負(fù)載均衡軟件,可以運行于大部分主流的Linux操作系統(tǒng)上(CentOS、Ubuntu、Debian、OpenSUSE、Fedora、麒麟、歐拉、UOS)。
HAProxy提供了L4(TCP)和L7(HTTP)兩種負(fù)載均衡能力,具備豐富的功能。HAProxy具備媲美商用負(fù)載均衡器的性能和穩(wěn)定性。
二、工作原理
HAProxy的工作原理是通過分析傳入的請求,并使用配置的規(guī)則來決定如何處理請求。它可以根據(jù)多種策略(如輪詢、最小連接數(shù)、源IP地址等)將請求分發(fā)到后端服務(wù)器。HAProxy還支持會話保持,它可以確保具有相同會話標(biāo)識符的請求都被發(fā)送到同一個后端服務(wù)器,以確保用戶的一致性體驗。
三、工作流程
HAProxy的工作流程如下:
監(jiān)聽端口:HAProxy監(jiān)聽一個或多個端口,接收傳入的請求。
請求分發(fā):根據(jù)配置的負(fù)載均衡規(guī)則,HAProxy將請求分發(fā)到一個或多個后端服務(wù)器。
響應(yīng)返回:后端服務(wù)器處理請求并將響應(yīng)返回給HAProxy。
響應(yīng)傳輸:HAProxy將后端服務(wù)器的響應(yīng)傳輸給客戶端。
Haproxy是一款可以供高可用性、負(fù)載均衡和基于TCP和HTTP應(yīng)用的代理軟件
- 適用于負(fù)載較大的站點
- 運行在硬件上可支持?jǐn)?shù)以萬計的并發(fā)連接請求
2、Haproxy的特性
可靠性和穩(wěn)定性非常好,可以與硬件級的F5負(fù)載均衡設(shè)備相媲美
最高可以同時維護40000-50000個并發(fā)連接,單位時間內(nèi)處理的最大請求數(shù)為20000個,最大處理能力可達10Git/s
支持多達8 種負(fù)載均衡算法,同時也支持會話保持
支持虛擬主機功能,從而實現(xiàn)web負(fù)載均衡更加靈活
支持連接拒絕、全透明代理等獨特功能
擁有強大的ACL支持,用于訪問控制等特性
環(huán)境說明:
虛擬機版本 | IP | 服務(wù) |
---|---|---|
centos8(DR) | 192.168.136.139 | haproxy |
centos8(RS1) | 192.168.136.140 | httpd |
centos8 (RS2) | 192.168.136.142 | httpd |
所有的虛擬機關(guān)閉防火墻和selinux
[root@DR ~]# systemctl stop --now firewalld
[root@DR ~]# systemctl disable firewalld
Removed /etc/systemd/system/multi-user.target.wants/firewalld.service.
Removed /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service.
[root@DR ~]# setenforce 0
[root@RS1 ~]# systemctl stop --now firewalld
[root@RS1 ~]# systemctl disable firewalld
Removed /etc/systemd/system/multi-user.target.wants/firewalld.service.
Removed /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service.
[root@RS1 ~]# setenforce 0
[root@RS2 ~]# systemctl stop --now firewalld
[root@RS2 ~]# systemctl disable firewalld
Removed /etc/systemd/system/multi-user.target.wants/firewalld.service.
Removed /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service.
[root@RS2 ~]# setenforce 0
在DR上面部署haproxy
# 創(chuàng)建haproxy用戶
[root@DR ~]# useradd -r -M -s /sbin/nologin haproxy
# 安裝依賴包
[root@DR ~]# yum -y install make gcc pcre-devel bzip2-devel openssl-devel systemd-devel --allowerasing
# 下載haproxy官網(wǎng)的穩(wěn)定版本的安裝包
[root@DR ~]# wget https://www.haproxy.org/download/2.7/src/haproxy-2.7.10.tar.gz
# 解壓
[root@DR ~]# tar -xf haproxy-2.7.10.tar.gz
[root@DR ~]# ll
total 4104
-rw-------. 1 root root 1246 Jul 27 09:41 anaconda-ks.cfg
drwxrwxr-x. 13 root root 4096 Aug 9 10:05 haproxy-2.7.10
-rw-r--r--. 1 root root 4191948 Aug 9 10:25 haproxy-2.7.10.tar.gz
[root@DR ~]# cd haproxy-2.7.10
# 編譯
[root@DR haproxy-2.7.10]# make clean
[root@DR haproxy-2.7.10]# make -j $(nproc) TARGET=linux-glibc USE_OPENSSL=1 USE_ZLIB=1 USE_PCRE=1 USE_SYSTEMD=1
過程省略........
# 指定目錄安裝
[root@DR haproxy-2.7.10]# make install PREFIX=/usr/local/haproxy
# 設(shè)置環(huán)境變量
[root@DR haproxy-2.7.10]# ln -s /usr/local/haproxy/sbin/* /usr/sbin/
[root@DR haproxy-2.7.10]# which haproxy
/usr/sbin/haproxy
# 配置內(nèi)核參數(shù)
[root@DR haproxy-2.7.10]# cd
[root@DR ~]# echo 'net.ipv4.ip_nonlocal_bind = 1' >> /etc/sysctl.conf
[root@DR ~]# echo 'net.ipv4.ip_forward = 1' >> /etc/sysctl.conf
[root@DR ~]# sysctl -p
net.ipv4.ip_nonlocal_bind = 1
net.ipv4.ip_forward = 1
# 提供配置文件
[root@DR ~]# mkdir /etc/haproxy
[root@DR ~]# cat > /etc/haproxy/haproxy.cfg <<EOF
#------------mkdir /etc/haproxy
cd haproxy-2.7.10
[root@DR ~]# mkdir /etc/haproxy
mkdir: cannot create directory ‘/etc/haproxy’: File exists
[root@DR ~]# cat /etc/haproxy/haproxy.cfg
#--------------全局配置----------------
global
log 127.0.0.1 local0 info
#log loghost local0 info
maxconn 20480
#chroot /usr/local/haproxy
pidfile /var/run/haproxy.pid
#maxconn 4000
user haproxy
group haproxy
daemon
#---------------------------------------------------------------------
#common defaults that all the 'listen' and 'backend' sections will
#use if not designated in their block
#---------------------------------------------------------------------
defaults
mode http
log global
option dontlognull
option httpclose
option httplog
#option forwardfor
option redispatch
balance roundrobin
timeout connect 10s
timeout client 10s
timeout server 10s
timeout check 10s
maxconn 60000
retries 3
#--------------統(tǒng)計頁面配置------------------
listen admin_stats
bind 0.0.0.0:8189
stats enable
mode http
log global
stats uri /haproxy_stats
stats realm Haproxy\ Statistics
stats auth admin:admin
#stats hide-version
stats admin if TRUE
stats refresh 30s
#---------------web設(shè)置-----------------------
listen webcluster
bind 0.0.0.0:80
mode http
#option httpchk GET /index.html
log global
maxconn 3000
balance roundrobin
cookie SESSION_COOKIE insert indirect nocache
server web01 192.168.136.140:80 check inter 2000 fall 5
server web02 192.168.136.142:8080 check inter 2000 fall 5
#server web01 192.168.80.102:80 cookie web01 check inter 2000 fall 5
[root@DR ~]#
# 配置加入systemctl管理
[root@DR ~]# vim /usr/lib/systemd/system/haproxy.service
[root@DR ~]# cat /usr/lib/systemd/system/haproxy.service
[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/run/haproxy.pid
ExecReload=/bin/kill -USR2 $MAINPID
[Install]
WantedBy=multi-user.target
# 重新加載
[root@DR ~]# systemctl daemon-reload
# 配置日志記錄功能
[root@DR ~]# vim /etc/rsyslog.conf
local0.* /var/log/haproxy.log (添加這行)
# 重啟日志服務(wù)
[root@DR ~]# systemctl restart rsyslog
# 重啟haproxy服務(wù)
[root@DR ~]# systemctl restart haproxy.service
[root@DR ~]# systemctl enable haproxy.service
Created symlink /etc/systemd/system/multi-user.target.wants/haproxy.service → /usr/lib/systemd/system/haproxy.service.
[root@DR ~]# ss -antl
State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
LISTEN 0 2048 0.0.0.0:80 0.0.0.0:*
LISTEN 0 128 0.0.0.0:22 0.0.0.0:*
LISTEN 0 2048 0.0.0.0:8189 0.0.0.0:*
LISTEN 0 128 [::]:22 [::]:*
[root@DR ~]#
訪問負(fù)載均衡器的http頁面測試
訪問DR的ip,會將請求轉(zhuǎn)發(fā)給后端服務(wù)器,第一次分配給了RS1,多次刷新,分配給RS2
在RS1和RS2中部署httpd
[root@RS1 ~]# yum -y install httpd
[root@RS1 ~]# systemctl start httpd
[root@RS1 html]# ss -antl
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 511 *:80 *:*
LISTEN 0 128 [::]:22 [::]:*
[root@RS1 html]# echo "RS1" > /var/www/html/index.html
[root@RS2 ~]# yum -y install httpd
[root@RS2 ~]# systemctl start httpd
[root@RS2 ~]# ss -antl
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 511 *:80 *:*
LISTEN 0 128 [::]:22 [::]:*
[root@RS2 ~]# echo "RS2" >> /var/www/html/index.html
網(wǎng)頁訪問!
這里要把RS1或者RS2 端口號該變,避免沖突
[root@RS2 ~]# vim /etc/httpd/conf/httpd.conf
Listen 8080
# 重啟以下httpd服務(wù)
RS1和RS2生成證書
# 在RS1
[root@RS1 ~]# mkdir -p /etc/pki/CA
[root@RS1 ~]# cd /etc/pki/CA/
[root@RS1 CA]# mkdir private
[root@RS1 CA]# (umask 077;openssl genrsa -out private/cakey.pem 2048)
Generating RSA private key, 2048 bit long modulus (2 primes)
............+++++
.............+++++
e is 65537 (0x010001)
[root@RS1 CA]# ls private/
cakey.pem
[root@RS1 CA]# openssl req -new -x509 -key private/cakey.pem -out cacert.pem -days 365
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:HB
Locality Name (eg, city) [Default City]:WH
Organization Name (eg, company) [Default Company Ltd]:www.tq.com
Organizational Unit Name (eg, section) []:www.tq.com
Common Name (eg, your name or your server's hostname) []:www.tq.com
Email Address []:6@32.com
[root@RS1 CA]# ls
cacert.pem private
# 生成密鑰
[root@RS1 CA]# ls private/
cakey.pem
[root@RS1 CA]# mkdir certs newcerts crl
[root@RS1 CA]# touch index.txt && echo 01 > serial
[root@RS1 CA]# cd /etc/httpd/ && mkdir ssl && cd ssl
[root@RS1 ssl]# (umask 077;openssl genrsa -out httpd.key 2048)
Generating RSA private key, 2048 bit long modulus (2 primes)
...................................................+++++
............................................................+++++
e is 65537 (0x010001)
# 生成證書簽署請求
[root@RS1 ssl]# openssl req -new -key httpd.key -days 365 -out httpd.csrIgnoring -days; not generating a certificate
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:HB
Locality Name (eg, city) [Default City]:WH
Organization Name (eg, company) [Default Company Ltd]:www.tq.com
Organizational Unit Name (eg, section) []:www.tq.com
Common Name (eg, your name or your server's hostname) []:www.tq.com
Email Address []:6@32.com
Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
# CA簽署它提交上來的證書
[root@RS1 ssl]# openssl ca -in httpd.csr -out httpd.crt -days 365
Using configuration from /etc/pki/tls/openssl.cnf
Check that the request matches the signature
Signature ok
Certificate Details:
Serial Number: 1 (0x1)
Validity
Not Before: Oct 11 16:07:17 2023 GMT
Not After : Oct 10 16:07:17 2024 GMT
Subject:
countryName = CN
stateOrProvinceName = HB
organizationName = www.tq.com
organizationalUnitName = www.tq.com
commonName = www.tq.com
emailAddress = 6@32.com
X509v3 extensions:
X509v3 Basic Constraints:
CA:FALSE
Netscape Comment:
OpenSSL Generated Certificate
X509v3 Subject Key Identifier:
53:45:17:71:FB:27:89:71:F7:A4:35:0D:9D:42:F6:58:BF:2E:97:94
X509v3 Authority Key Identifier:
keyid:CD:BF:E9:20:5C:76:D3:E0:77:53:6D:FD:D5:4E:EE:0A:0C:CA:C7:33
Certificate is to be certified until Oct 10 16:07:17 2024 GMT (365 days)
Sign the certificate? [y/n]:y
1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated
[root@RS1 ssl]#
# 安裝證書服務(wù)
[root@RS1 ssl]# yum -y install httpd-devel mod_ssl
# 修改配置文件
[root@RS1 ssl]# vim /etc/httpd/conf.d/ssl.conf
[root@RS1 ssl]# grep -Ev '^$|^#' /etc/httpd/conf.d/ssl.conf
Listen 443 https
SSLPassPhraseDialog exec:/usr/libexec/httpd-ssl-pass-dialog
SSLSessionCache shmcb:/run/httpd/sslcache(512000)
SSLSessionCacheTimeout 300
SSLCryptoDevice builtin
<VirtualHost _default_:443>
DocumentRoot "/var/www/html/www.tq.com" #取消注釋,修改自己域名
ServerName www.tq.com:443 # 這行
ErrorLog logs/ssl_error_log
TransferLog logs/ssl_access_log
LogLevel warn
SSLEngine on
SSLHonorCipherOrder on
SSLCipherSuite PROFILE=SYSTEM
SSLProxyCipherSuite PROFILE=SYSTEM
SSLCertificateFile /etc/httpd/ssl/httpd.crt # 修改對的路徑
SSLCertificateKeyFile /etc/httpd/ssl/httpd.key # 這行也是
<FilesMatch "\.(cgi|shtml|phtml|php)$">
SSLOptions +StdEnvVars
</FilesMatch>
<Directory "/var/www/cgi-bin">
SSLOptions +StdEnvVars
</Directory>
BrowserMatch "MSIE [2-5]" \
nokeepalive ssl-unclean-shutdown \
downgrade-1.0 force-response-1.0
CustomLog logs/ssl_request_log \
"%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"
</VirtualHost>
[root@RS1 ssl]#
# 創(chuàng)建https的網(wǎng)頁文件
[root@RS1 ssl]# mkdir -p /var/www/html/www.wanf.com
[root@RS1 ssl]# rm -rf /var/www/html/www.wanf.com
[root@RS1 ssl]# mkdir -p /var/www/html/www.tq.com
[root@RS1 ssl]# echo "this is RS1 https" > /var/www/html/www.tq.com/index.html
[root@RS1 ssl]# systemctl restart httpd
在RS2中生成證書
# scp 把RS1中的證書復(fù)制過來
[root@RS2 ~]# cd /etc/httpd/ && mkdir ssl && cd ssl
[root@RS2 ssl]# scp root@192.168.136.140:/etc/httpd/ssl/httpd.crt /etc/httpd/ssl/
The authenticity of host '192.168.136.140 (192.168.136.140)' can't be established.
ECDSA key fingerprint is SHA256:k8DoJlJ1tVvvBL4kfXDMXrbAW4iWqhw2fnatIewmqRo.
Are you sure you want to continue connecting (yes/no/[fingerprint])? y
Please type 'yes', 'no' or the fingerprint: yes
Warning: Permanently added '192.168.136.140' (ECDSA) to the list of known hosts.
root@192.168.136.140's password:
httpd.crt 100% 4579 1.5MB/s 00:00
[root@RS2 ssl]# scp root@192.168.136.140:/etc/httpd/ssl/httpd.key /etc/httpd/ssl/
root@192.168.136.140's password:
httpd.key 100% 1679 1.5MB/s 00:00
[root@RS2 ssl]# ll
total 12
-rw-r--r--. 1 root root 4579 Oct 11 19:18 httpd.crt
-rw-------. 1 root root 1679 Oct 11 19:19 httpd.key
# 安裝證書服務(wù)
[root@RS2 ssl]# yum -y install httpd-devel mod_ssl
# 修改配置文件,和RS1一樣
[root@RS2 ssl]# vim /etc/httpd/conf.d/ssl.conf
[root@RS2 ssl]# grep -Ev '^$|^#' /etc/httpd/conf.d/ssl.conf
Listen 443 https
SSLPassPhraseDialog exec:/usr/libexec/httpd-ssl-pass-dialog
SSLSessionCache shmcb:/run/httpd/sslcache(512000)
SSLSessionCacheTimeout 300
SSLCryptoDevice builtin
<VirtualHost _default_:443>
DocumentRoot "/var/www/html/www.tq.com"
ServerName www.tq.com:443
ErrorLog logs/ssl_error_log
TransferLog logs/ssl_access_log
LogLevel warn
SSLEngine on
SSLHonorCipherOrder on
SSLCipherSuite PROFILE=SYSTEM
SSLProxyCipherSuite PROFILE=SYSTEM
SSLCertificateFile /etc/httpd/ssl/httpd.crt
SSLCertificateKeyFile /etc/httpd/ssl/httpd.key
<FilesMatch "\.(cgi|shtml|phtml|php)$">
SSLOptions +StdEnvVars
</FilesMatch>
<Directory "/var/www/cgi-bin">
SSLOptions +StdEnvVars
</Directory>
BrowserMatch "MSIE [2-5]" \
nokeepalive ssl-unclean-shutdown \
downgrade-1.0 force-response-1.0
CustomLog logs/ssl_request_log \
"%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"
</VirtualHost>
[root@RS2 ssl]#
#創(chuàng)建https網(wǎng)頁文件
[root@RS2 ssl]# mkdir -p /var/www/html/www.tq.com
[root@RS2 ssl]# echo "this is RS2 https" > /var/www/html/www.tq.com/index.html
# 重啟服務(wù)
[root@RS2 ssl]# systemctl restart httpd
配置https 負(fù)載均衡規(guī)則 (DR主機上)
[root@DR ~]# vim /etc/haproxy/haproxy.cfg
[root@DR ~]# cat /etc/haproxy/haproxy.cfg
#--------------全局配置----------------
global
log 127.0.0.1 local0 info
#log loghost local0 info
maxconn 20480
#chroot /usr/local/haproxy
pidfile /var/run/haproxy.pid
#maxconn 4000
user haproxy
group haproxy
daemon
#---------------------------------------------------------------------
#common defaults that all the 'listen' and 'backend' sections will
#use if not designated in their block
#---------------------------------------------------------------------
defaults
mode tcp // 修改為tcp
log global
option dontlognull
option httpclose
option httplog
#option forwardfor
option redispatch
balance roundrobin
timeout connect 10s
timeout client 10s
timeout server 10s
timeout check 10s
maxconn 60000
retries 3
#--------------統(tǒng)計頁面配置------------------
listen admin_stats
bind 0.0.0.0:8189
stats enable
mode http
log global
stats uri /haproxy_stats
stats realm Haproxy\ Statistics
stats auth admin:admin
#stats hide-version
stats admin if TRUE
stats refresh 30s
#---------------web設(shè)置-----------------------
listen webcluster
bind 0.0.0.0:443 //修改為443
mode tcp // 改為tcp
#option httpchk GET /index.html
log global
maxconn 3000
balance roundrobin
cookie SESSION_COOKIE insert indirect nocache
server web03 192.168.136.140:443 check inter 2000 fall 5 //修改
server web04 192.168.136.142:443 check inter 2000 fall 5 //修改
#server web01 192.168.80.102:8080 cookie web01 check inter 2000 fall 5
# 重啟服務(wù)
[root@DR ~]# systemctl restart haproxy.service
# 查看端口
[root@DR ~]# ss -antl
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 2048 0.0.0.0:443 0.0.0.0:*
LISTEN 0 2048 0.0.0.0:8189 0.0.0.0:*
LISTEN 0 128 [::]:22 [::]:*
[root@DR ~]#
訪問負(fù)載均衡https的頁面
刷新
IP地址后接上8189/haproxy_stats就可以訪問
里面是haproxy的負(fù)載集群主機的狀態(tài)
# 查看
[root@DR ~]# cat /etc/haproxy/haproxy.cfg
#--------------統(tǒng)計頁面配置------------------
listen admin_stats
bind 0.0.0.0:8189 //端口信息
stats enable
mode http
log global
stats uri /haproxy_stats
stats realm Haproxy\ Statistics
stats auth admin:admin //用戶信息
#stats hide-version
stats admin if TRUE
stats refresh 30s
#---------------web設(shè)置-----------------------
listen webcluster
文章來源:http://www.zghlxwxcb.cn/news/detail-814524.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-814524.html
到了這里,關(guān)于haproxy 負(fù)載均衡&配置http+https負(fù)載集群實戰(zhàn)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!