如何在CentOS 7中将HAProxy设置为Nginx的负载平衡器

Written in C by Willy Tarreau, HAProxy, also known as High Availability Proxy is a fast and lightweight HTTP load balancer and proxy server. It has a low CPU usage and is occasioned by a small memory footprint. The load balancer is used by popular websites such as StackOverflow, Twitter, Github, and Tumblr to mention just but a few.

HAProxy由Willy Tarreau用C语言编写,也称为高可用性代理,它是一种快速,轻量级的HTTP负载平衡器和代理服务器。 它具有较低的CPU使用率,并且内存占用较小。 流行的网站(例如StackOverflow,Twitter,Github和Tumblr)使用负载平衡器仅举几例。

In this guide, we will show you how to set up HAProxy as a load balancer for Nginx web server on CentOS 7. The load balancer will sit in front of 2 Nginx web servers and equitably distribute HTTP requests to the servers.

在本指南中,我们将向您展示如何在CentOS 7上将HAProxy设置为Nginx Web服务器的负载平衡器。该负载平衡器将位于2个Nginx Web服务器的前面,并公平地向服务器分发HTTP请求。

HAProxy平衡算法 (HAProxy Balance Algorithm)

This is the algorithm used by the load balancer for selection of the web servers when distributing workloads.

这是负载均衡器在分配工作负载时用于选择Web服务器的算法。

1. Roundrobin (1. Roundrobin)

This is the simplest of the algorithms. Basically, each new connection will be handled by the next web server. For instance, if you have 4 back-end servers, Each of them will handle requests in succession. When the last web server on the list is reached, the load balancer will start from the top again with the first web server.

这是最简单的算法。 基本上,每个新连接都将由下一个Web服务器处理。 例如,如果您有4个后端服务器,则每个服务器将连续处理请求。 当到达列表中的最后一个Web服务器时,负载平衡器将从第一个Web服务器的顶部重新开始。

2. Lastconn (2. Lastconn)

Here a new request will be handled by the server with the least number of connections. This comes in handy when load and times of requests differ by great variations.

在这里,连接数量最少的服务器将处理一个新请求。 当请求的负载和时间相差很大时,这很方便。

入门 (Getting started)

To start off, perform a pre-flight checklist and ensure that you have the following.

首先,请执行飞行前检查清单,并确保您具备以下条件。

1. CentOS 7 servers

1. CentOS 7服务器

HostnameServer IP address
load-balancer173.82.168.96
web-server-1173.82.2.236
web-server-2173.82.94.57
主机名 服务器的IP地址
负载均衡器 173.82.168.96
网络服务器1 173.82.2.236
网络服务器2 173.82.94.57

2. SSH access to all the servers

2. SSH访问所有服务器

Below is a graphical representation of the setup.

以下是设置的图形表示。

步骤1:在负载均衡器中配置/ etc / hosts文件 (Step 1: Configure /etc/hosts file in the load balancer)

Log in to the load balancer using SSH and add the Nginx web servers IP addresses and hostnames as shown.

使用SSH登录到负载均衡器,并添加Nginx Web服务器的IP地址和主机名,如图所示。

vim /etc/hosts


173.82.2.236    web-server-1

173.82.94.57    web-server-2

Save and exit vim text editor.

保存并退出vim文本编辑器。

Next, log into each of the Web servers (web-server-1 and web-server-2) and edit the /etc/hosts file to point to the load balancer.

接下来,登录到每个Web服务器(web-server-1和web-server-2)并编辑/etc/hosts文件以指向负载平衡器。

173.82.168.96   load-balancer

Save and exit the text editor.

保存并退出文本编辑器。

步骤2:在负载平衡器服务器上安装和配置HAProxy (Step 2: Install and configure HAProxy on load balancer server)

The HAProxy repository is readily available on the CentOS repository. To install and set up HAProxy, first, log in and update the system repositories.

HAProxy存储库可以在CentOS存储库上使用。 要安装和设置HAProxy,首先,登录并更新系统存储库。

yum update -y

Next, install HAProxy using the command:

接下来,使用以下命令安装HAProxy:

yum -y install haproxy

Sample Output

样本输出

Once the installation is successful and complete, head out to the haproxy directory.

安装成功并完成后,请转到haproxy目录。

cd /etc/haproxy

Backup the haproxy.cfg file by renaming it to haproxy.cfg.bak

通过将haproxy.cfg文件重命名为haproxy.cfg.bak来备份它

mv haproxy.cfg  haproxy.cfg.bak

Next, create a new HAproxy configuration file.

接下来,创建一个新的HAproxy配置文件。

vim haproxy.cfg
#---------------------------------------------------------------------
# Global settings
#---------------------------------------------------------------------
global
    log         127.0.0.1 local2     #Log configuration

    chroot      /var/lib/haproxy
    pidfile     /var/run/haproxy.pid
    maxconn     4000
    user        haproxy             #Haproxy running under user and group "haproxy"
    group       haproxy
    daemon

    # turn on stats unix socket
    stats socket /var/lib/haproxy/stats

#---------------------------------------------------------------------
# common defaults that all the 'listen' and 'backend' sections will
# use if not designated in their block
#---------------------------------------------------------------------
defaults
    mode                    http
    log                     global
    option                  httplog
    option                  dontlognull
    option http-server-close
    option forwardfor       except 127.0.0.0/8
    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                 3000

#---------------------------------------------------------------------
#HAProxy Monitoring Config
#---------------------------------------------------------------------
listen haproxy3-monitoring *:8080                #Haproxy Monitoring run on port 8080
    mode http
    option forwardfor
    option httpclose
    stats enable
    stats show-legends
    stats refresh 5s
    stats uri /stats                             #URL for HAProxy monitoring
    stats realm Haproxy\ Statistics
    stats auth Password123: Password123            #User and Password for login to the monitoring dashboard
    stats admin if TRUE
    default_backend app-main                    #This is optionally for monitoring backend

#---------------------------------------------------------------------
# FrontEnd Configuration
#---------------------------------------------------------------------
frontend main
    bind *:80
    option http-server-close
    option forwardfor
    default_backend app-main

#---------------------------------------------------------------------
# BackEnd round robin as balance algorithm
#---------------------------------------------------------------------
backend app-main
    balance roundrobin                                     #Balance algorithm
    option httpchk HEAD / HTTP/1.1\r\nHost:\ localhost    #Check the server application is up and healty - 200 status code
    server web-server-1 173.82.2.236:80 check                 #Nginx1
    server web-server-2 173.82.94.57:80 check                 #Nginx2

Take note of the web servers which have been specified in the last 2 lines as shown in the output.

记下最后两行中指定的Web服务器,如输出所示。

Save and exit the text editor.

保存并退出文本编辑器。

Next, We are going to configure the rsyslog daemon to log the HAProxy statistics.

接下来,我们将配置rsyslog守护程序以记录HAProxy统计信息。

Edit the rsyslog.conf file to enable the UDP port 514 to be used by rsyslog.

编辑rsyslog.conf文件以启用rsyslog.conf的UDP端口514。

vim /etc/rsyslog.conf

To allow UDP connection via port 154, uncomment the following lines.

要允许通过端口154的UDP连接,请取消注释以下几行。

$ModLoad imudp
$UDPServerRun 514

Save and exit the text editor.

保存并退出文本编辑器。

Next, create a new HAProxy configuration file for syslog.

接下来,为syslog创建一个新的HAProxy配置文件。

vim  /etc/rsyslog.d/haproxy.conf

Paste the following configuration

粘贴以下配置

local2.=info     /var/log/haproxy-access.log    #For Access Log
local2.notice    /var/log/haproxy-info.log      #For Service Info - Backend, loadbalancer

Save and exit the text editor.

保存并退出文本编辑器。

Proceed and restart rsyslog.

继续并重新启动rsyslog。

systemctl restart rsyslog

Next, start and enable Haproxy to start at boot up.

接下来,启动并启用Haproxy以在启动时启动。

systemctl start haproxy
systemctl enable haproxy

To confirm that HaProxy is up and running, execute:

要确认HaProxy已启动并正在运行,请执行:

systemctl status haproxy

In the next step, we are going to install Nginx to our web servers.

下一步,我们将Nginx安装到我们的Web服务器上。

步骤3:安装和配置Nginx (Step 3: Installing and configuring Nginx)

The only crucial step remaining is the installation of Nginx on each of our web servers.

剩下的唯一关键步骤是在每台Web服务器上安装Nginx。

But first, install EPEL repository as shown

但首先,如图所示安装EPEL存储库

yum install epel-release

Next, install Nginx

接下来,安装Nginx

yum install nginx -y

Sample output

样品输出

With Nginx installed on both servers, we are going to modify the index.html files in each of the Nginx web servers in order to create a distinction between each server when simulating with the HAproxy load balancer.

在两台服务器上都安装了Nginx的情况下,我们将修改每台Nginx Web服务器中的index.html文件,以便在使用HAproxy负载均衡器进行仿真时在每台服务器之间建立区分。

Move to the html directory as shown:

移至html目录,如下所示:

cd /usr/share/nginx/html/

Backup the index.html file

备份index.html文件

mv index.html index.html.bak

Next, create a new index.html file and paste some sample content.

接下来,创建一个新的index.html文件并粘贴一些示例内容。

对于Web服务器1 (For Web Server 1)

echo "web-server-1. Hey ! This is your first web server" > index.html

对于Web Server 2 (For Web Server 2)

echo "web-server-2. Hey ! This is your second web server" > index.html

Next, start Nginx in both web servers and confirm if the service is running

接下来,在两个Web服务器中启动Nginx并确认服务是否正在运行

systemctl start  nginx
systemctl status nginx

测试负载平衡 (Testing Load balancing)

To verify that everything went well, run the following command repeatedly.

要验证一切正常,请重复运行以下命令。

curl 173.82.168.96

Your output should be similar to this.

您的输出应与此类似。

As you can observe keenly, with each subsequent run on the curl command, the output alternates between the first and the second web server content Perfect!

正如您可以敏锐地观察到的那样,每当随后在curl命令上运行该命令时,输出将在第一个和第二个Web服务器内容“ Perfect!”之间交替显示。

Now, let’s try testing using the web browser.

现在,让我们尝试使用网络浏览器进行测试。

https://load-balancer-IP-address

https://load-balancer-IP-address

This will display the content on either of the web servers, In this case, web-server-2.

这将在两个Web服务器(在本例中为Web-server-2)上显示内容。

Now, try refreshing once or twice and the output will point to the other web server, in this case, web-server-1.

现在,尝试刷新一次或两次,输出将指向另一个Web服务器,在本例中为Web-server-1。

Awesome! This confirms that our load balancer is able to equitably distribute HTTP requests between our web servers.

太棒了! 这证实了我们的负载均衡器能够在我们的Web服务器之间公平地分配HTTP请求。

TO gather more statistics of the load balancer browser the following URL

要收集负载均衡器浏览器的更多统计信息,请访问以下URL

https://load-balancer-IP:8080/stats

Use the Password123 as the username and Password as we defined in haproxy.cfg configuration file.

使用Password123作为我们在haproxy.cfg配置文件中定义的用户名和密码。

This sums up this tutorial on how to set up HAProxy load balancer for Nginx on CentOS 7. Feel free to try it out and share this guide on your social networks. As always, your feedback will be appreciated.

总结了本教程,该教程介绍了如何在CentOS 7上为Nginx设置HAProxy负载均衡器。可以随时尝试并在您的社交网络上共享本指南。 一如既往,您的反馈将不胜感激。

翻译自: https://www.journaldev.com/29943/haproxy-load-balancer-nginx-centos

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值