search
HomeOperation and MaintenanceNginxHow to use nginx to implement a load balancing cluster with dynamic and static separation

1. Experimental environment

1.1 System and services

The operating system and services used this time:

This experiment requires a total of 3 servers, one nginx is used as a load balancing distributor and a distributor for dynamic and static separation, and two apache servers are used as back-end servers. nginx is used to realize load balancing and static and dynamic separation of the two apache servers.

Operating system: centos7.6
nginx version: 1.22 version
apache version: 2.4.6 that comes with the system by default
php version: 5.4.16## that comes with the system by default

# Both the apache and php versions can be upgraded to the latest version, which can be downloaded and installed from the official website.

1.2 Architecture diagram to be implemented this time

How to use nginx to implement a load balancing cluster with dynamic and static separation

#Generally, our servers are divided into many types, including file servers, picture servers, and database servers.

There are also various services:

  • Static file processing: You can use nginx or apache

  • Dynamic file processing : apache, tomcat

  • Image file processing: squid

In this article, we use nginx to implement a load balancing cluster with dynamic and static separation.

2. Detailed explanation of nginx load balancing

2.1 What is load balancing?

Server load balancing refers to the technology of allocating requests from clients to multiple servers to improve system performance, increase system reliability, and avoid single points of failure.

Through load balancing, multiple servers can jointly process client requests, thereby improving the overall performance and availability of the system.

In load balancing, multiple servers are usually formed into a server cluster. The client sends a request to the load balancer. The load balancer will allocate the request to one or more servers in the server cluster based on a certain algorithm. Processed on multiple servers. There are many load balancing algorithms, common ones include polling, random, minimum number of connections, etc.

Load balancing strategies can become more sophisticated, for example using advanced features such as session persistence, health checks and dynamic weight adjustments. By configuring and adjusting actual needs, the flexibility and efficiency of the load balancing system can be improved.

2.2 5 ways of load balancing

Nginx’s 5 ways of upstream load, the top 3 most commonly used methods are currently:

1) Polling (default)
Every Requests are assigned to different backend servers one by one in chronological order. If the backend server goes down, it can be automatically eliminated.
2) weight
Specifies the polling probability, weight is proportional to the access ratio, and is used when the performance of the back-end server is uneven.
3) ip_hash
Each request is allocated according to the hash result of the accessed IP, so that each visitor has fixed access to a back-end server, which can solve the session problem.
4) air (third party)
Requests are allocated according to the response time of the backend server, and those with short response times are allocated first.
5) url_hash (third party)
Distribute requests according to the hash result of the accessed URL, so that the same URL is directed to the same back-end server. It is more effective when the back-end server is cached

Three . Install nginx as a traffic distributor

3.1 Prepare to install dependent tools before installing nginx

[root@mufeng41 ~]#  yum -y install gcc gcc-c++ autoconf automake

[root@mufeng41 ~]# yum -y install zlib zlib-devel openssl openssl-devel pcre pcre-devel

When Mu Feng Xiaoyue did this step of installation, she forgot to mount the image, which wasted a lot. time, so you need to mount it in advance and configure the yum source.

Upload the nginx compressed package and decompress it

How to use nginx to implement a load balancing cluster with dynamic and static separation

[root@mufeng41 ~]# ll nginx-1.12.2.tar.gz 
-rw-r--r--. 1 root root 981687 8月  27 2019 nginx-1.12.2.tar.gz
[root@mufeng41 ~]# tar xf nginx-1.12.2.tar.gz  -C /usr/local/src/

Log in and view

root@mufeng41 ~]# cd !$
cd /usr/local/src/
[root@mufeng41 src]# ls
nginx-1.12.2
[root@mufeng41 src]# cd nginx-1.12.2/
[root@mufeng41 nginx-1.12.2]# ls
auto  CHANGES  CHANGES.ru  conf  configure  contrib  html  LICENSE  man  README  src
[root@mufeng41 nginx-1.12.2]#

3.2 Start compiling

./configure --prefix=/usr/local/nginx  --with-http_dav_module --with-http_stub_status_module --with-http_addition_module --with-http_sub_module --with-http_flv_module  --with-http_mp4_module

Yes Explanation of parameters:

  • –with-http_dav_module enables ngx_http_dav_module support (adds PUT, DELETE, MKCOL: create collection, COPY and MOVE methods). It is closed by default and needs to be compiled and turned on

  • –with-http_stub_status_module Enable ngx_http_stub_status_module support (get the working status of nginx since the last startup)

  • –with-http_addition_module Enable ngx_http_addition_module support (acts as an output filter, supports incomplete buffering, responds to requests in parts)

  • ##–with-http_sub_module Enable ngx_http_sub_module support (allows replacing some of the nginx response with some other text Text)
  • –with-http_flv_module Enable ngx_http_flv_module support (provides time-based offset file seeking memory usage)
  • –with -http_mp4_module enables support for mp4 files (providing time-based offset files for seeking memory usage)
  • 3.3 Start compiling and installing nginx

Use

make && make install

Installation<pre class='brush:php;toolbar:false;'>[root@mufeng41 nginx-1.12.2]# make &amp;&amp; make install</pre>How to determine whether the execution is successful?

Answer:

echo $?

3.4 Generate a running nginx user

[root@mufeng41 nginx-1.12.2]# useradd -u 8000 -s /sbin/nologin  nginx
[root@mufeng41 nginx-1.12.2]# id nginx
uid=8000(nginx) gid=8000(nginx) 组=8000(nginx)
[root@mufeng41 nginx-1.12.2]#

3.5 Start nginx and test

If you don’t know where the nginx configuration file and startup script are, you can search for them. Use

find / -name nginx.conf

.Start the service

[root@itlaoxin163 ~]# find / -name nginx.conf
/usr/local/nginx/conf/nginx.conf

# 启动
[root@mufeng41 nginx-1.12.2]# /usr/local/nginx/sbin/nginx 

[root@mufeng41 nginx-1.12.2]# netstat -antup |grep 80
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      25286/nginx: master 
udp        0      0 0.0.0.0:58076           0.0.0.0:*

View the effect

[root@mufeng41 nginx-1.12.2]# systemctl stop firewalld.service
[root@mufeng41 nginx-1.12.2]# curl -I 127.0.0.1
HTTP/1.1 200 OK
Server: nginx/1.12.2
Date: Fri, 24 Mar 2023 11:06:29 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Fri, 24 Mar 2023 11:01:53 GMT
Connection: keep-alive
ETag: "641d8321-264"
Accept-Ranges: byte

四. 配置nginx成为分发器

4.1 先备份配置文件

[root@mufeng41 conf]# pwd
/usr/local/nginx/conf
[root@mufeng41 conf]# cp nginx.conf nginx.conf.bak
[root@mufeng41 conf]#

4.2 把nginx设置成分发器,实现动静分离

配置如下图:

配置分发器

How to use nginx to implement a load balancing cluster with dynamic and static separation

location / {
            root   html;
            index  index.html index.htm;


        if ($request_uri ~* \.html$){
                   proxy_pass http://htmlservers;
           }
        if ($request_uri ~* \.php$){
                   proxy_pass http://phpservers;
           }
                   proxy_pass http://picservers;

        }

注释:
location 的作用是根据请求的 URI,将请求转发到不同的后端服务器上进行处理。具体解释如下:

  • location /:表示所有请求(URI)都会被这个 location 块所匹配。

  • root html:表示当访问的 URI对应的文件不存在时,会在 nginx 安装目录下的 html 目录中查找对应的文件。

  • index index.html

  • index.htm:表示当访问的 URI 对应的目录中没有指定的默认文件时,会尝试访问 index.html 或 index.htm 文件。

  • if ($request_uri ~* .html$):表示如果请求的 URI 包含 .html,则执行下面的语句。

  • proxy_pass http://htmlservers:表示将请求转发到名为 htmlservers 的后端服务器处理。

  • if ($request_uri ~* .php$):表示如果请求的 URI 包含 .php,则执行下面的语句。

  • proxy_pass http://phpservers:表示将请求转发到名为 phpservers 的后端服务器处理。

  • proxy_pass http://picservers:表示将请求转发到名为 picservers 的后端服务器处理,这个语句没有条件限制,如果以上两个if 语句都不匹配,则会执行这个语句。

接下来设置负载均衡对应的IP

定义负载均衡设备的IP

在nginx配置文件最后一行}前添加一下内容:

How to use nginx to implement a load balancing cluster with dynamic and static separation

代码如下:

 upstream  htmlservers {  
         server 192.168.1.42:80;   
         server 192.168.1.43:80;
 }
 upstream  phpservers{
         server 192.168.1.42:80;
         server 192.168.1.43:80;
 }
 upstream  picservers {
         server 192.168.1.42:80;
         server 192.168.1.43:80;
 }

配置文件是否有错误

[root@mufeng41 conf]# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

重启nginx

[root@mufeng41 conf]# /usr/local/nginx/sbin/nginx -s reload

五. 配置两台http服务器

接下来,需要在 mufeng42和mufeng43上操作

5.1 配置mufeng42服务器 配置web服务器:

[root@mufeng42 ~]# yum install httpd  php -y

生成静态测试文件

[root@mufeng42 ~]# echo 192.168.1.42  > /var/www/html/index.html

在创建一个php文件:

[root@itlaoxin162 ~]# vim /var/www/html/test.php

写入内容:

echo "我是42服务器";echo "我是沐风晓月"<?phpphpinfo();?>

启动apache

[root@mufeng42 ~]# systemctl  restart httpd

5.2 配置mufeng43服务器

安装http并生成静态文件

[root@mufeng43 ~]# yum install httpd php -y
[root@mufeng43 ~]# echo 192.168.1.43 > /var/www/html/index.html

建立php文件

[root@mufeng43 ~]# cd /var/www/html/

[root@mufeng43 html]# vi mufeng.php
[root@mufeng43 html]# cat mufeng.php 
echo "我是43服务器";
<?php
phpinfo();
?>

启动配置文件

[root@mufeng43 html]# systemctl restart httpd

5.3 测试

到目前为止,nginx负载均衡就结束了,接下来就可以测试了:

测试静态页面

浏览器输入: http://192.168.1.41/ 进行测试

How to use nginx to implement a load balancing cluster with dynamic and static separation

How to use nginx to implement a load balancing cluster with dynamic and static separation

测试转发动态页面:

浏览器输入 http://192.168.1.41/test.php

How to use nginx to implement a load balancing cluster with dynamic and static separation

The above is the detailed content of How to use nginx to implement a load balancing cluster with dynamic and static separation. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
NGINX Unit's Purpose: Running Web ApplicationsNGINX Unit's Purpose: Running Web ApplicationsApr 30, 2025 am 12:06 AM

The purpose of NGINXUnit is to simplify the deployment and management of web applications. Its advantages include: 1) Supports multiple programming languages, such as Python, PHP, Go, Java and Node.js; 2) Provides dynamic configuration and automatic reloading functions; 3) manages application lifecycle through a unified API; 4) Adopt an asynchronous I/O model to support high concurrency and load balancing.

NGINX: An Introduction to the High-Performance Web ServerNGINX: An Introduction to the High-Performance Web ServerApr 29, 2025 am 12:02 AM

NGINX started in 2002 and was developed by IgorSysoev to solve the C10k problem. 1.NGINX is a high-performance web server, an event-driven asynchronous architecture, suitable for high concurrency. 2. Provide advanced functions such as reverse proxy, load balancing and caching to improve system performance and reliability. 3. Optimization techniques include adjusting the number of worker processes, enabling Gzip compression, using HTTP/2 and security configuration.

NGINX vs. Apache: A Look at Their ArchitecturesNGINX vs. Apache: A Look at Their ArchitecturesApr 28, 2025 am 12:13 AM

The main architecture difference between NGINX and Apache is that NGINX adopts event-driven, asynchronous non-blocking model, while Apache uses process or thread model. 1) NGINX efficiently handles high-concurrent connections through event loops and I/O multiplexing mechanisms, suitable for static content and reverse proxy. 2) Apache adopts a multi-process or multi-threaded model, which is highly stable but has high resource consumption, and is suitable for scenarios where rich module expansion is required.

NGINX vs. Apache: Examining the Pros and ConsNGINX vs. Apache: Examining the Pros and ConsApr 27, 2025 am 12:05 AM

NGINX is suitable for handling high concurrent and static content, while Apache is suitable for complex configurations and dynamic content. 1. NGINX efficiently handles concurrent connections, suitable for high-traffic scenarios, but requires additional configuration when processing dynamic content. 2. Apache provides rich modules and flexible configurations, which are suitable for complex needs, but have poor high concurrency performance.

NGINX and Apache: Understanding the Key DifferencesNGINX and Apache: Understanding the Key DifferencesApr 26, 2025 am 12:01 AM

NGINX and Apache each have their own advantages and disadvantages, and the choice should be based on specific needs. 1.NGINX is suitable for high concurrency scenarios because of its asynchronous non-blocking architecture. 2. Apache is suitable for low-concurrency scenarios that require complex configurations, because of its modular design.

NGINX Unit: Key Features and CapabilitiesNGINX Unit: Key Features and CapabilitiesApr 25, 2025 am 12:17 AM

NGINXUnit is an open source application server that supports multiple programming languages ​​and provides functions such as dynamic configuration, zero downtime updates and built-in load balancing. 1. Dynamic configuration: You can modify the configuration without restarting. 2. Multilingual support: compatible with Python, Go, Java, PHP, etc. 3. Zero downtime update: Supports application updates that do not interrupt services. 4. Built-in load balancing: Requests can be distributed to multiple application instances.

NGINX Unit vs. Other Application ServersNGINX Unit vs. Other Application ServersApr 24, 2025 am 12:14 AM

NGINXUnit is better than ApacheTomcat, Gunicorn and Node.js built-in HTTP servers, suitable for multilingual projects and dynamic configuration requirements. 1) Supports multiple programming languages, 2) Provides dynamic configuration reloading, 3) Built-in load balancing function, suitable for projects that require high scalability and reliability.

NGINX Unit: The Architecture and How It WorksNGINX Unit: The Architecture and How It WorksApr 23, 2025 am 12:18 AM

NGINXUnit improves application performance and manageability with its modular architecture and dynamic reconfiguration capabilities. 1) Modular design includes master processes, routers and application processes, supporting efficient management and expansion. 2) Dynamic reconfiguration allows seamless update of configuration at runtime, suitable for CI/CD environments. 3) Multilingual support is implemented through dynamic loading of language runtime, improving development flexibility. 4) High performance is achieved through event-driven models and asynchronous I/O, and remains efficient even under high concurrency. 5) Security is improved by isolating application processes and reducing the mutual influence between applications.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment