【Nginx基础】负载均衡服务器(2)

1 案例描述

使用一台虚拟机,使用端口模拟不同的服务,设置四个nginx配置文件,作用分别如下:

端口作用配置文件
8888负载均衡/etc/nginx/conf.d/slb.conf
8081应用服务1,服务地址:/opt/app/slb1;/etc/nginx/conf.d/slb1.conf
8082应用服务2,服务地址:/opt/app/slb2;/etc/nginx/conf.d/slb2.conf
8083备份服务器/etc/nginx/conf.d/slb3.conf

用户访问8888,可以转发到8081和8082上


2 配置文件

(1) 负载均衡服务nginx配置文件 slb.conf

#设置负载均衡
upstream slbserver {
#ip_hash; #根据Ip来分配,有存储cookie登录等场景适用
#默认是轮询
server 127.0.0.1:8081 weight=2 max_fails=2 fail_timeout=2;
server 127.0.0.1:8082 weight=1 max_fails=2 fail_timeout=2;
#调用backup服务器,可以是本机或其他服务器。
server 127.0.0.1:8083 backup;
}
server {
#访问入口
listen 8888;
server_name localhost;
#charset koi8-r;
#access_log /var/log/nginx/host.access.log main;
location / {
proxy_pass http://slbserver;#通过upstrean定义的服务器组名调用后端服务器
proxy_set_header X-Real-IP $remote_addr; #传递客户端的ip地址
}
}


(2) 应用服务1Nginx配置文件 slb1.conf

server {
listen 8081;
server_name localhost;
#charset koi8-r;
#access_log /var/log/nginx/host.access.log main;
location / {
root /opt/app/slb1;
index index.html index.htm;
}
}


(3) 应用服务2Nginx配置文件slb2.conf

server {
listen 8082;
server_name localhost;
#charset koi8-r;
#access_log /var/log/nginx/host.access.log main;
location / {
root /opt/app/slb2;
index index.html index.htm;
}
}


(4)  备份服务器Nginx配置文件 slb3.conf

server {
listen 8083;
server_name localhost;
#charset koi8-r;
#access_log /var/log/nginx/host.access.log main;
location / {
root /opt/app/slb3;
index index.html index.htm;
}
}


(5) 测试访问文件 index.html

分别放到:/opt/app/slb1;/opt/app/slb2;/opt/app/slb3;三个文件夹下;并请将server 1修改一下,区分开就可以。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Server1</title>
</head>
<body>
<h1>SERVER 1</h1>
</body>
</html>


3 重启nginx并测试

nginx -s reload

浏览器中输入:http://127.0.0.1:8888,此时可以看到,被分发到应用服务1和2上,也可以分别测试一下ip_hash的功能,以及权重weight的作用。这里就不测试了。


相关推荐

  • 生成图片

    from PIL import Image, ImageColor, ImageDraw, ImageFont, ImageFilterdef create_image_with_text(size, color, text, font_path, font_size, text_color, shadow_color, output_path): """ Create a new image of specified size and color with centered text that has a border and shadow. :param size: A tuple con

  • 获取指定目录下的所有图片信息

    1 获取指定目录下的所有图片信息// 获取指定目录下的所有图片信息 public function getImagesInfo($directory) { $images = []; // 创建递归目录迭代器 $iterator = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator($directory, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::LEAVES_ONLY ); // 遍历目录中的每个文件 foreach (

  • Thinkphp各版本的PHP要求

    ThinkPHP 8.0:运行环境要求PHP8.0+,兼容PHP8.3ThinkPHP 6.1:运行环境要求PHP7.2+,兼容PHP8.1ThinkPHP 6.0:运行环境要求PHP7.2+,兼容PHP8.1ThinkPHP 5.1:运行环境要求PHP5.6+,兼容PHP8.0ThinkPHP 5.0:运行环境要求PHP5.4+,兼容PHP7.3