search
HomeBackend DevelopmentPHP TutorialCentos+nginx configure load balancing from scratch

Understanding of nginx load balancing

nginx is a lightweight, high-performance webserver. It can mainly do the following two things:

  • As an http server (same effect as apache)
  • Act as a reverse proxy server to achieve load balancing

Now nginx can be seen everywhere, and you often see the words nginx displayed on webpages after downtime. This also shows that nginx is accepted by more and more users due to its high performance, simple use and configuration, and open source. used.

The first one acts as an http server and combines with the php-fpm process to process incoming requests. nginx itself does not parse PHP. It just acts as a server to accept requests from the client. If it is a PHP request, Then it is handed over to the php process for processing, and the result after the php processing is completed is sent to the client. This is very simple. After installing nginx+php-fpm, configure the respective configuration files and start it. The operating principle can be seen in the following explanation:

Nginx does not support direct calling or parsing of external programs. All external programs (including PHP) must be called through the FastCGI interface. The FastCGI interface is a socket under Linux (this socket can be a file socket or an ip socket). In order to call a CGI program, a FastCGI wrapper is also needed (a wrapper can be understood as a program used to start another program). This wrapper is bound to a fixed socket, such as a port or file socket. When Nginx sends a CGI request to this socket, the wrapper receives the request through the FastCGI interface, and then spawns a new thread. This thread calls the interpreter or external program to process the script and read the return data; then, the wrapper The returned data is passed to Nginx along the fixed socket through the FastCGI interface; finally, Nginx sends the returned data to the client. This is the entire operation process of Nginx+FastCGI, as shown in the figure below.

The above paragraph explains the operating mechanism of nginx+fastcgi. The request will be matched in the nginx configuration file and processed accordingly, such as returning the error file directly (there is a little difference between this and the above, I guess nginx can perform analysis similar to the above picture on static files such as HTML), and use the PHP process to process PHP requests (there can be multiple PHP processes here).

The second is to use reverse proxy load balancing. This is actually very simple. To put it simply, you define a group of servers, match the requests, and transfer the requests to any one of the servers for processing to reduce the load on each server. To reduce the pressure, first take a look at the definition of reverse proxy online:

The Reverse Proxy method refers to using a proxy server to accept connection requests on the Internet, then forward the request to the server on the internal network, and return the results obtained from the server to the client requesting a connection on the Internet , at this time the proxy server appears as a reverse proxy server to the outside world.

Reverse proxy is the opposite of forward proxy (or proxy). You must have heard of proxy. In order to access resource B more conveniently, resource B is indirectly accessed through resource A. The characteristic is that the user knows what he will eventually access. What is the website, but reverse proxy users do not know what processing is done behind the proxy server. The real processing server of the service in the reverse proxy is placed on the intranet, and the external network can only access the reverse proxy server, which greatly Improved security.

Install software

nginx installation is very simple

1. The environment required to install nginx, pcre (for rewrite), zlib (for compression), ssl, you can also download, compile and install this yourself

yum -y install zlib;

yum –y install pcre;

yum –y install openssl;

2. Download and install nginx-*.tar.gz.

tar –zxvf nginx-1.2.8.tar.gz –C ./;

cd nginx-1.2.8;

./congigure --prefix=/usr/local/nginx;

make && make install;

3. Configuration

When configuring here, you only need to modify the content between http{}. The first place to modify is to set up the server group and add

between http nodes.

upstream myServer{
                                                                                                                                                                                                                                            #Here                                            

Upstream in nginx supports the following methods: polling (by default, all servers are accessed one by one in chronological order. If a server is down, it will be automatically eliminated), weight (the location probability of the server is proportional to the weight, this It can be configured when the server configuration is uneven), ip_hash (hash calculation is performed on each requested IP, and the corresponding server is allocated according to certain rules), fair (requests are allocated according to the response time (rt) of each server) , rt knows priority allocation), url_hash (distributes requests according to the hash value of the accessed URL), I use the default rotation method here.

Point the request to myServer

location / {
            proxy_pass   http://myServer;
    }

The complete document (with comments removed) is as follows:

worker_processes  <span>1</span><span>;
events {
    worker_connections  </span><span>1024</span><span>;
}
http {
    include       mime.types;
    default_type  application</span>/octet-<span>stream;
    sendfile        on;
    keepalive_timeout  </span><span>65</span><span>;
    upstream myServer{
       server www.myapp1.com:</span><span>80</span><span>;
       server www.myapp2.com:</span><span>8080</span><span>;
    }
    server {
        listen       </span><span>80</span><span>;
        server_name  my22;
        location </span>/<span> {
            proxy_pass   http:</span><span>//</span><span>myServer;</span>
<span>        }
    }
}</span>

Set up reverse proxy backend as load balancing between two servers

You can see that there are two server addresses in the previous step, www.myapp1.com:80 and www.myapp2.com:8080. I installed the above nginx on the virtual machine. I installed these two servers on this server. In the win8 system of the computer, using apache's virtualhost, two domain names are set up. The codes under the two domain names are independent of each other, and the settings are also very simple:

1. Set up apache configuration file

I am using the xampp integrated environment. There are two places to modify. Add the listening port in httpd.conf

Listen 8080

That is to say, this place monitors two ports

Listen 80
Listen 8080

Check whether the following sentence is open. If not, open it. Open it as shown below

<span># Virtual hosts
Include conf</span>/extra/httpd-vhosts.conf

Add the following content in httpd-vhosts.conf,

<virtualhost>80><span>
    ServerName www.myapp1.com #对应的域名,负载均衡的服务器地址
    DocumentRoot E:\soft\xampp\htdocs\www.myapp1.com #代码文件夹
</span></virtualhost>
<virtualhost>8080><span>
    ServerName www.myapp2.com
    DocumentRoot E:\soft\xampp\htdocs\www.myapp2.com
</span></virtualhost>

Modify the windows hosts file and add the following content

<span>127.0</span>.<span>0.1</span><span>        www.myapp1.com
</span><span>127.0</span>.<span>0.1</span>        www.myapp2.com

Modify the /etc/hosts file of Linux and add the following content

<span>192.168</span>.<span>1.12</span><span>        www.myapp1.com #这里前面的地址对应我win8本机的ip地址
</span><span>192.168</span>.<span>1.12</span>        www.myapp2.com

I put a file index.php in www.myapp1.com:80 [E:softxampphtdocswww.myapp1.comindex.php]

 A file index.php is also placed in www.myapp2.com:8080 [E:softxampphtdocswww.myapp2.comindex.php]

 The content in the file is basically the same, except that I'm the myapp2 is different. One is myapp1 and the other is myapp2.

 If you can enter www.myapp1.com:80 and www.myapp2.com:8080 in the win8 browser to see different effects

 And when you see the following result under centos (beautified by yourself), it means that the configuration is successful

[root@bogon nginx]# curl www.myapp1.com:<span>80</span><span>
I</span><span>'</span><span>m the myapp1<br>【view】1</span>
[root@bogon nginx]# curl www.myapp2.com:<span>8080</span><span>
I</span><span>'</span><span>m the myapp2<br>【view】1</span>

<span>php
</span><span>session_save_path</span>("./"<span>);
</span><span>session_start</span><span>();
</span><span>header</span>("Content-type:text/html;charset=utf-8"<span>);
</span><span>if</span>(<span>isset</span>(<span>$_SESSION</span>['view'<span>])){
    </span><span>$_SESSION</span>['view'] = <span>$_SESSION</span>['view'] + 1<span>;
}</span><span>else</span><span>{
    </span><span>$_SESSION</span>['view'] = 1<span>;
}
</span><span>echo</span> "I'm the myapp2<br>"<span>;
</span><span>echo</span> "【view】{<span>$_SESSION</span>['view']}";

See the effect

After everything is ok, you can access it through the browser to see the effect

Forgot to mention, the address of nginx proxy server is http://192.168.1.113,

After entering http://192.168.1.113/index.php in the browser, keep refreshing, you will find that it will be in

I'm the myapp2、I'm the myapp1

  When these two pages are exchanged back and forth, the view will be increased once without refreshing twice. This also proves the default rotation training method mentioned earlier, but there is another common problem here. When the user visits the website , without processing, the session will be saved on different servers (I use two different folders to simulate two servers here), and there may be multiple sets of session data. How to solve this problem? The next article will talk about it This question is actually very simple.

 The copyright of this article belongs to the author iforever (luluyrt@163.com). Any form of reprinting is prohibited without the author's consent. After reprinting the article, the author and the original text link must be provided in an obvious position on the article page, otherwise the right to pursue legal liability is reserved. .

The above has introduced centos+nginx to configure load balancing from scratch, including all aspects. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
解决方法:您的组织要求您更改 PIN 码解决方法:您的组织要求您更改 PIN 码Oct 04, 2023 pm 05:45 PM

“你的组织要求你更改PIN消息”将显示在登录屏幕上。当在使用基于组织的帐户设置的电脑上达到PIN过期限制时,就会发生这种情况,在该电脑上,他们可以控制个人设备。但是,如果您使用个人帐户设置了Windows,则理想情况下不应显示错误消息。虽然情况并非总是如此。大多数遇到错误的用户使用个人帐户报告。为什么我的组织要求我在Windows11上更改我的PIN?可能是您的帐户与组织相关联,您的主要方法应该是验证这一点。联系域管理员会有所帮助!此外,配置错误的本地策略设置或不正确的注册表项也可能导致错误。即

Windows 11 上调整窗口边框设置的方法:更改颜色和大小Windows 11 上调整窗口边框设置的方法:更改颜色和大小Sep 22, 2023 am 11:37 AM

Windows11将清新优雅的设计带到了最前沿;现代界面允许您个性化和更改最精细的细节,例如窗口边框。在本指南中,我们将讨论分步说明,以帮助您在Windows操作系统中创建反映您的风格的环境。如何更改窗口边框设置?按+打开“设置”应用。WindowsI转到个性化,然后单击颜色设置。颜色更改窗口边框设置窗口11“宽度=”643“高度=”500“&gt;找到在标题栏和窗口边框上显示强调色选项,然后切换它旁边的开关。若要在“开始”菜单和任务栏上显示主题色,请打开“在开始”菜单和任务栏上显示主题

如何在 Windows 11 上更改标题栏颜色?如何在 Windows 11 上更改标题栏颜色?Sep 14, 2023 pm 03:33 PM

默认情况下,Windows11上的标题栏颜色取决于您选择的深色/浅色主题。但是,您可以将其更改为所需的任何颜色。在本指南中,我们将讨论三种方法的分步说明,以更改它并个性化您的桌面体验,使其具有视觉吸引力。是否可以更改活动和非活动窗口的标题栏颜色?是的,您可以使用“设置”应用更改活动窗口的标题栏颜色,也可以使用注册表编辑器更改非活动窗口的标题栏颜色。若要了解这些步骤,请转到下一部分。如何在Windows11中更改标题栏的颜色?1.使用“设置”应用按+打开设置窗口。WindowsI前往“个性化”,然

OOBELANGUAGE错误Windows 11 / 10修复中出现问题的问题OOBELANGUAGE错误Windows 11 / 10修复中出现问题的问题Jul 16, 2023 pm 03:29 PM

您是否在Windows安装程序页面上看到“出现问题”以及“OOBELANGUAGE”语句?Windows的安装有时会因此类错误而停止。OOBE表示开箱即用的体验。正如错误提示所表示的那样,这是与OOBE语言选择相关的问题。没有什么可担心的,你可以通过OOBE屏幕本身的漂亮注册表编辑来解决这个问题。快速修复–1.单击OOBE应用底部的“重试”按钮。这将继续进行该过程,而不会再打嗝。2.使用电源按钮强制关闭系统。系统重新启动后,OOBE应继续。3.断开系统与互联网的连接。在脱机模式下完成OOBE的所

Windows 11 上启用或禁用任务栏缩略图预览的方法Windows 11 上启用或禁用任务栏缩略图预览的方法Sep 15, 2023 pm 03:57 PM

任务栏缩略图可能很有趣,但它们也可能分散注意力或烦人。考虑到您将鼠标悬停在该区域的频率,您可能无意中关闭了重要窗口几次。另一个缺点是它使用更多的系统资源,因此,如果您一直在寻找一种提高资源效率的方法,我们将向您展示如何禁用它。不过,如果您的硬件规格可以处理它并且您喜欢预览版,则可以启用它。如何在Windows11中启用任务栏缩略图预览?1.使用“设置”应用点击键并单击设置。Windows单击系统,然后选择关于。点击高级系统设置。导航到“高级”选项卡,然后选择“性能”下的“设置”。在“视觉效果”选

Windows 11 上的显示缩放比例调整指南Windows 11 上的显示缩放比例调整指南Sep 19, 2023 pm 06:45 PM

在Windows11上的显示缩放方面,我们都有不同的偏好。有些人喜欢大图标,有些人喜欢小图标。但是,我们都同意拥有正确的缩放比例很重要。字体缩放不良或图像过度缩放可能是工作时真正的生产力杀手,因此您需要知道如何对其进行自定义以充分利用系统功能。自定义缩放的优点:对于难以阅读屏幕上的文本的人来说,这是一个有用的功能。它可以帮助您一次在屏幕上查看更多内容。您可以创建仅适用于某些监视器和应用程序的自定义扩展配置文件。可以帮助提高低端硬件的性能。它使您可以更好地控制屏幕上的内容。如何在Windows11

10种在 Windows 11 上调整亮度的方法10种在 Windows 11 上调整亮度的方法Dec 18, 2023 pm 02:21 PM

屏幕亮度是使用现代计算设备不可或缺的一部分,尤其是当您长时间注视屏幕时。它可以帮助您减轻眼睛疲劳,提高易读性,并轻松有效地查看内容。但是,根据您的设置,有时很难管理亮度,尤其是在具有新UI更改的Windows11上。如果您在调整亮度时遇到问题,以下是在Windows11上管理亮度的所有方法。如何在Windows11上更改亮度[10种方式解释]单显示器用户可以使用以下方法在Windows11上调整亮度。这包括使用单个显示器的台式机系统以及笔记本电脑。让我们开始吧。方法1:使用操作中心操作中心是访问

如何在Safari中关闭iPhone的隐私浏览身份验证?如何在Safari中关闭iPhone的隐私浏览身份验证?Nov 29, 2023 pm 11:21 PM

在iOS17中,Apple为其移动操作系统引入了几项新的隐私和安全功能,其中之一是能够要求对Safari中的隐私浏览选项卡进行二次身份验证。以下是它的工作原理以及如何将其关闭。在运行iOS17或iPadOS17的iPhone或iPad上,如果您在Safari浏览器中打开了任何“无痕浏览”标签页,然后退出会话或App,Apple的浏览器现在需要面容ID/触控ID认证或密码才能再次访问它们。换句话说,如果有人在解锁您的iPhone或iPad时拿到了它,他们仍然无法在不知道您的密码的情况下查看您的隐私

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools