Nginx 集群

公司⽹站⽇常PV 60万,你的Nginx服务器如何优化。

本节内容
01
集群介绍
02
Nginx集群原理
03
实现基于Nginx分发器的web集群
04

01 集群介绍

【系统部署知识汇总】第11章——Nginx 集群_数据

单点故障解决⽅案

 1) 部署⼀台备份服务器,宕机直接切换
2) 部署多台服务器,根据DNS的轮询解析机制去实现⽤户分发

问题:

1⽅案:服务器利⽤率低,成本⾼,切换不及时,服务器压⼒依然⼤
2⽅案:

并⾏处理解决⽅案

 1) 上述的DNS轮询解析⽅案
2)多机阵列---集群模式

【系统部署知识汇总】第11章——Nginx 集群_数据_02

集群

 将多个物理机器组成⼀个逻辑计算机,实现负载均衡和容错
计算机集群简称集群,是⼀种计算机系统, 它通过⼀组松散集成的计算机软件或硬件连接起来⾼度紧密地协作完成计算
⼯作。在某种意义上,他们可以被看作是⼀台计算机。 (百度解释)
组成要素
1)VIP: 1个IP地址
2)分发器: nginx
3)数据服务器: Web服务器

02 Nginx集群原理

Nginx集群:

 在该集群中Nginx扮演的⻆⾊是: 分发器
任务:接受请求、分发请求、响应请求
功能模块:
1) ngx_http_upstream_module 基于应⽤层分发模块
2) ngx_stream_core_module 基于传输层分发模块 (1.9开始提供)

Nginx集群原理

 Nginx集群其实是:虚拟主机+反向代理+upstream分发模块组成的
虚拟主机:接受和响应请求
反向代理: 带⽤户去数据服务器拿数据
upstream:
 数据⾛向
1)虚拟主机接受⽤户请求
2)虚拟主机去找反向代理
3) 反向代理让去找upstream
4)upstream 告诉 ⼀个数据服务器IP
5)Nginx去找数据服务器 并发起⽤户的请求
6) 数据服务器接受请求并处理请求
7)数据服务器响应请求给Nginx
8)Nginx响应请求给⽤户

03 Nginx集群实现

声明

 实验机器: Vmware 虚拟机 2核4G
⽹卡:桥接
系统:centos7.5
防⽕墙:关闭
Selinux:关闭
网段:192.168.10.0/24

主机名 IP ⻆色
Master.ayitula.com 192.168.10.40 主分发器
Backup.ayitula.com 192.168.10.41 备分发器
Web01.ayitula.com 192.168.10.42 数据服务器1
Web02.ayitula.com 192.168.10.43 数据服务器2

配置1个web集群

1) Nginx 安装
2) 配置业务服务器⻚⾯
3 配置Nginx分发器
4 测试分发

配置web业务机器

#web02
[root@web02 ~]# sh nginx_install
[root@web02 ~]# echo web02 > /usr/local/nginx/html/index.html
[root@web02 ~]# yum -y install elinks &>/dev/null
[root@web02 ~]# /usr/local/nginx/sbin/nginx
[root@web02 ~]# elinks http://localhost -dump
web02

配置分发器

Syntax: upstream name { ... }
Default:
Context: http

#upstream 模块
upstream web {
server 192.168.10.42;
server 192.168.10.43;
}

server {
listen 80;
server_name localhost;
location / {
proxy_pass http://web;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}

03 Nginx集群测试

集群分发测试

[root@web02 ~]# elinks http://192.168.10.40 -dump
web01
[root@web02 ~]# elinks http://192.168.10.40 -dump
web02
[root@web02 ~]# elinks http://192.168.10.40 -dump
web01
[root@web02 ~]# elinks http://192.168.10.40 -dump
web02