nginx
2022-03-08 本文已影响0人
wsj1211
nginx 简介
- 准备工作
对外开放端口
firewall-cmd --add-port=8080/tcp --permanent
firewall-cmd --reload
查看已经开放的端口号
firewall-cmd --list-all - 配置文件:
三部分组成
- 全局块:
从开始到events块之间的内容,主要回设置一些影响nginx服务整体运行的配置指令
eg: worker processes 1; // 值越大 可以支持的并发处理量也越多 - events块:
设计的指令主要影响Nginx服务器与用户的网络连接
eg:worker connections 1024; 支持的最大连接数 - http块:
Nginx 服务器配置中最频繁的部分
http 块也包含全局块,server块
- 案例
- 浏览器访问www.123.com 实际访问服务器的8080端口
- 修改host文件 添加一行
xxx.xxx.xxx.xxx www.123.com
- server 修改为
~~~
server {
listen 80;
server_name xxx.xxx.xxx.xxx;
location / {
- 修改host文件 添加一行
反向代理
root html;
proxy_pass http://xxx.xxx.xxx:8080;
index index.html index.htm;
}
}
~~~
- 浏览器访问
http://192.168.1.1:9091/edu/a.html 实际访问的是192.168.1.1的8080服务
http://192.168.1.1:9091/wsj/a.html实际访问的是192.168.1.1的8081服务
修改server
~~~
server {
listen 9091;
server_name 192.168.1.1;
location ~/edu/ {
proxy_pass http://127.0.0.1:8080;
}
location ~/wsj/ {
proxy_pass http://127.0.0.1:8081;
}
}
~~~
负载均衡
修改配置文件
#在http块添加upstream server中location的proxy_pass 配成upstream的名字
http {
upstream dalaoyang-server {
server localhost:10001;
server localhost:10002;
}
server {
listen 10000;
server_name localhost;
location / {
proxy_pass http://dalaoyang-server;
proxy_redirect default;
}
}
}
负载均衡的方式
- 默认轮询
所有请求都按照时间顺序分配到不同的服务上,如果服务Down掉,可以自动剔除 - 权重
指定每个服务的权重比例,weight和访问比率成正比,通常用于后端服务机器性能不统一,将性能好的分配权重高来发挥服务器最大性能,如下配置后10002服务的访问比率会是10001服务的二倍。
upstream dalaoyang-server {
server localhost:10001 weight=1;
server localhost:10002 weight=2;
}
- ip_hash
每个请求都根据访问ip的hash结果分配,经过这样的处理,每个访客固定访问一个后端服务,适合于登陆? 如下配置(ip_hash也可以和weight配合使用)。
upstream dalaoyang-server {
ip_hash;
server localhost:10001 weight=1;
server localhost:10002 weight=2;
}
- fair
按后端服务器的响应时间来分配请求,响应时间短的优先分配。
upstream dalaoyang-server {
server localhost:10001;
server localhost:10002;
fair;
}
动静分离
就是配置为访问服务器的一个文件夹 即可访问文件夹下的图片和html文件等
高可用模式
两台服务器+ keepalived(配置相同的虚拟ip)
两台服务器都启动nginx 并配置一样的环境(nginx+ keepalived)
keepalived分为master和backup 一台服务器宕机 自动转为获取另外一台服务器
- keepalived 配置
分三块
全局块
nginx内部模式
- 一个master + 多个worker
好处 不需要加锁 每个进程都是独立的 - 设置worker数量
和服务器的cpu数量一致最好
worker processon 4;
- 发送请求 占用了worker的几个连接数
2
个或者4
个 - 假如 一个worker的最大连接数是1024,支持的最大并发请求是多少
// 正常worker_connects*worker_processes/2
// 反向代理worker_connects*worker_processes/4