nginx的负载均衡实战

142 阅读1分钟

结构两个文件:

image-20210708165417466.png

upstream.conf的配置

upstream backends {
     server localhost:10086;
     server localhost:10087;
     server localhost:10088;
}
server {
     listen 80;
     location / {
     proxy_pass http://backends;
 } }

backend.conf

server {
     listen localhost:10086;
     location / {
     root /var/www/html/hello/;
     try_files $uri $uri/ =404;
 } }
server {
     listen localhost:10087;
     location / {
      root /var/www/html/nihao/;
     try_files $uri $uri/ =404;
 } }
server {
     listen localhost:10088;
     location / {
     root /var/www/html/huanying/;
     try_files $uri $uri/ =404;
 } }

在相对应的文件夹下,生成对应的html文件

mkdir -p /var/www/html/hello/
echo '<h1>backend_hello</h1>' > /var/www/html/hello/index.html
mkdir -p /var/www/html/nihao/
echo '<h1>backend_nihao</h1>' > /var/www/html/nihao/index.html
mkdir -p /var/www/html/huanying/
echo '<h1>backend_huanying</h1>' > /var/www/html/huanying/index.html

重新加载配置文件

/usr/sbin/nginx -t
/usr/sbin/nginx -s reload
netstat -tnulp | grep nginx

结果:(默认轮询的方式)

  • 第一次请求

    • image-20210708165636583.png
  • 第二次请求

    • image-20210708165644078.png
  • 第三次请求

    • image-20210708165745942.png