Nginx安装/负载均衡/反向代理配置与调优
【Nginx安装】
Linux下直接使用包管理安装
sudo apt-get install nginx
使用whereis命令查看安装位置
whereis nginx
#sbin下代表nginx可执行程序
#etc/nginx下有nginx.conf配置文件
#usr/share下有html文件夹,可配置nginx的静态资源/页面
通过包管理安装的nginx已注册为服务,可用systemctl命令进行操作。
修改nginx.conf快速重启可使用命令:nginx -s reload
【Nginx均衡负载】
(一)NGINX均衡负载介绍
[1]情景:
当一个应用访问量很大时,一个服务器无法应对如此大的访问量时,就需要多个服务器同时运行这同一个Web应用。Nginx的作用就是将用户的请求按照一定的规则转发给Web应用服务器,实现均衡负载。用户不再直接对Web服务器进行请求,而是对Nginx进行请求.
[2]特点:
用户请求提交给Nginx,而非直接到Web服务器
Nginx配置了多个运行相同应用的Web服务器,根据权值将请求转发给Web服务器
[3]图解:
其中的Session服务器是指HttpSession对象,该Session对象被单独独立出来作为服务器,实现Session共享。
Session共享的原因:同一个用户的所有请求被Nginx转发不一定是同一个Web服务器,若不进行Session共享,上次请求被转发的web服务器进行了Session域的存储操作,下次请求未转发到上次的web服务器,此时就造成了Session数据中的丢失
(二)NGINX均衡负载在Web应用的配置
HttpSession的共享需要借助Redis来实现,即Session的内容存储在Redis中,所有的RealServer(Web服务器)都需接入该Redis获得Session信息。
实现步骤:
【1】构建SpringBoot项目,并追加以下依赖
Redis相关依赖
<!--加入Redis相关依赖--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId><exclusions>
<!-- 排除redis自带的模板--><exclusion><groupId>io.lettuce</groupId><artifactId>lettuce-core</artifactId></exclusion></exclusions></dependency>
<!-- 使用jedis模板 --><dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId></dependency>
SessionData相关依赖
<!--Session共享-->
<dependency><groupId>org.springframework.session</groupId><artifactId>spring-session-data-redis</artifactId>
</dependency>
【2】配置Redis
在全局配置文件application.properties中添加redis相关配置
#其余默认配置,此处为redis相关配置
spring.redis.database=0
spring.redis.host=127.0.0.1
spring.redis.port=6379
#spring.redis.password= #redis默认密码为空
spring.redis.jedis.pool.max-active=8
spring.redis.jedis.pool.max-idle=8
spring.redis.jedis.pool.max-wait=-1ms
sprinq.redis.jedis.pool.min-idle=0
Tips:真实部署环境时,redis的ip都要定位到同一个主机,此处由于redis也在本机,所以为127.0.0.1
【3】配置tomcat的端口号
由于要模拟两个web服务器,电脑只有一台,因此需要设置不同端口来模拟,该web应用打两个jar包,这两个端口号不同,作为两个web服务器。本次演示用8081与8082
#tomcat配置,配置两个端口,代表不同的服务器
server.port=8082
(三)NGINX均衡负载配置(windows)
此处下载的是windows版本的NGINX
解压后进入安装目录找到nginx.conf文件
找到server节点:
server节点表示访问NGINX的配置,其包含以下配置:
指定NGINX的端口号【默认80】,和服务器名字(域名)【默认localhost】
指定转发上游location proxy_pass。即负载均衡到哪些web服务器上,及其权值【需要在server节点上面同级创建upstream节点来指定web服务器】
注意location后面的/,此处可以配外部访问Nginx服务的前缀(一般不以/结束)
具体格式如下:
upstream prprzuikaku.com{server 127.0.0.1:8081 weight=1;server 127.0.0.1:8082 weight=1;}
server {listen 80;server_name localhost;#charset koi8-r;#access_log logs/host.access.log main;location / {proxy_pass http://prprzuikaku.com;}
需要注意:
上游名字upStream与下面的proxy_pass要对应,具体值无所谓(是否为域名形式也无所谓)
若上游节点没有配置权值,默认策略为轮询,即一次A一次B一次A一次B
(四)测试
Tips:由于Nginx的请求转发具有一定的不确定性,所以可能要多次测试,直到看到两种端口得到的消息,则说明配置成功的。
[1]测试类:
该Controller共两个方法,一个用于向Session中存数据,一个用于从Session中取数据,其中有一个port的字段,从application.properties文件中注入,这个字段在取数据时也会打印出来。目的就是为了区别是哪个web服务器发送的。
@Controller
@RequestMapping("/test")
public class MyController {@Value("${server.port}")private String port;@GetMapping("/index")public String index(Model model){return "index";}@RequestMapping("/save")@ResponseBodypublic String saveToSession(@RequestParam("input")String input, HttpSession httpSession){httpSession.setAttribute("input",input);return "<h1 style='color:green'>输入的值已存入HttpSession</h1>";}@RequestMapping("/get")@ResponseBodypublic String getFromSession(@SessionAttribute("input")String input){return "<h1 style='color:blue'>"+"来自端口:"+port+"取值为:"+input+"</h1>";}
}
[2]index.html:
该页面就是主页,其中有一个表单用来提交存的值,另一个超链接则是用来获取存的值
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head><meta charset="UTF-8"><title>首页</title>
</head>
<body><h1>传入一个值存入session</h1>
<form id="myForm" method="post" th:action="@{/test/save}"><input type="text" name="input"/><button type="button" onclick="submitForm()">提交</button>
</form>
<div id="resultBox"></div>
<a th:href="@{/test/get}" target="_blank">获得session中的值</a>
</body><script type="text/javascript" th:src="@{/js/jquery-3.4.1.min.js}"></script>
<script type="text/javascript">function submitForm() {$.ajax({url:"[[@{/test/save}]]",type:"post",data:new FormData($("#myForm")[0]),dataType:"html",contentType:false,processData:false,success:function (data) {$("#resultBox").html(data);}});}
</script>
</html>
[3]验证方法
我们通过访问Nginx进入主页,此时不知道自己是被分发到哪个web服务器,但这不用管。直接访问"获取Session中的值"这个超链接,在取值时会得到服务器的端口号,直到看到两个端口号都显示过一次后,说明Nginx是配置成功的,HttpSession共享正常。
同时运行两个服务:作为两个服务器
请求转发到8082了
请求转发到8081了
【Nginx反向代理】
(一)NGINX反向代理介绍
【1】情景
一台服务器可能运行多个Web服务,这些Web服务可以通过不同的端口给到外界访问,但可能由于安全的原因,服务器只向外提供了一个用于Web访问的端口。多个web服务只能通过该端口进行访问,为了区别不同的项目,则需要配置不同的前缀映射到对应的端口,而这个操作就是Nginx的反向代理,这个向外界提供的端口就是Nginx服务的端口。【这些Web具体服务也可以来自不同的主机,Nginx相当于对这些分布各地的服务器做了一个统一的入口访问】
【2】特点
用户发起请求先到Nginx再去代理,而非直接到Web服务
通过Ip:Nginx端口/前缀/ 的方式访问到原服务器多个不同端口的web服务
Nginx可以直接挂载一个目录实现全静态网页的访问
【3】图解
(二)NGINX反向代理在Web应用的配置
在/nginx/conf/nginx.conf中进行配置
【初始配置文件(生效部分)】
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
【参数讲解】
server下的listen,此处配置是Nginx的访问端口
server下的server_name代表受信任的域,一般配置有哪些域名或ip可以访问到该nginx以空格隔开
默认的映射配置包含location /,error_page,location=/50x此处定向访问Nginx不加前缀时的首页,要让错误页面配置生效,则需要在nginx的html文件夹下创建50x.html,当然error_page可以追加设置其他http错误code
注意!:location的url应该以/作为结束,对于映射的服务地址,也应该以/作为结束(避免映射静态目录时由于无/而认为是文件)
【配置反向代理-案例】
指定对应的url前缀和服务地址(ip(domain):port),在server标签下新增location标签
#pilipililocation / {proxy_pass https://localhost:8081/;proxy_set_header Host $host:$server_port;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;proxy_set_header X-Forwarded-Proto $scheme;proxy_set_header X-Forwarded-Port $server_port;client_max_body_size 512m;}#docker监测location /docker/ {proxy_pass http://localhost:9000/;proxy_set_header Host $host:$server_port;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;proxy_set_header X-Forwarded-Proto $scheme;proxy_set_header X-Forwarded-Port $server_port;}#下载中心location /download/ {alias /home/nanoda/download/;autoindex on;autoindex_exact_size off;charset utf-8;}#定义通用的错误页面(error.html在/usr/share/nginx/html中)error_page 500 502 503 504 404 /error.html;location = /error.html {root html;charset utf-8;}
client_max_body_size是指上传文件的大小限制【可配置到location标签中,或放入http标签中】
需要注意:
【1】如果Nginx服务所使用的端口存在端口映射,请保证外网端口与内网端口相同,否则在外网访问时Nginx时,页面的重定向会走内网的端口,而忽略外网导致无法访问。此时需要指定nginx的服务端口就与外部端口相同。同端口号映射即可。(或增加Nginx配置处理也行)
方案1:nginx端口与外网端口相同,端口映射时同端口号
方案2:nginx对于该应用的location标签添加以下配置:
#web1location /web1/ {if (-d $request_filename) {rewrite [^/]$ $scheme://$http_host$uri/ permanent;}
【2】如果转发的服务中需要使用WebSocket,则在location下需增加两个配置:
proxy_set_header Connection "Upgrade";
proxy_set_header Upgrade $http_upgrade;
【Nginx配置Https】
【1】下载Nginx专用的证书文件
将其放置nginx目录中/conf/cert文件夹中。【cert文件夹需要手动创建】
【2】修改配置文件
在server标签中追加ssl的相关配置,并修改端口,绑定域名
server {listen 2333 ssl;server_name www.pilipili.live;ssl_certificate /home/nanoda/ssl/www.pilipili.live.pem;ssl_certificate_key /home/nanoda/ssl/www.pilipili.live.key;ssl_session_cache shared:SSL:1m;ssl_session_timeout 5m;ssl_protocols TLSv1 TLSv1.1 TLSv1.2; #加密协议配置ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE; #加密套件配置ssl_prefer_server_ciphers on;#打开...其他配置}
反向代理配置的location /需要使用https端口服务
location /web3/ {proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;proxy_pass https://localhost:4433/;client_max_body_size 300m;
}
配置http强制跳转至https
增加一个server标签用于配置http的访问,并在里面进行重定向
server {listen 80;server_name www.zuikakuedu.top;rewrite ^(.*)$ https://$host$1 permanent;
}
Tips:外界访问nginx证书使用nginx配置的ssl,与web服务器本身配置的ssl无关,除非直接访问本身web服务。
【Nginx调优配置】
调优后的nginx.conf
#工作进程数(与逻辑处理器相同)
worker_processes 1;
#进程处理器绑定(避免分配不均)
#worker_cpu_affinity 0001 0010 0100 1000;
#nginx_worker进程最大打开文件数
worker_rlimit_nofile 20480;events {accept_mutex on;multi_accept on;#单个进程允许的最大连接数worker_connections 20480;
}http {#关闭访问日志记录access_log off;#开启高效文件传输模式sendfile on;sendfile_max_chunk 5m;#数据尽快发送,提高效率tcp_nodelay on; include mime.types;default_type application/octet-stream;#优化服务器域名的散列大小server_names_hash_max_size 512;server_names_hash_bucket_size 128;#请求体最大大小(大文件上传时需关注) client_max_body_size 512m;client_header_buffer_size 4k;large_client_header_buffers 8 8k;client_body_buffer_size 256k;#会话生效时间 keepalive_timeout 30;#开启gzip压缩功能,对静态资源进行压缩gzip on;gzip_vary on;#压缩最小阈值设置(小于该大小则不压缩)gzip_min_length 5k;gzip_buffers 8 128k;gzip_proxied any;gzip_http_version 1.1;#压缩等级(1-10)gzip_comp_level 4;gzip_disable msie6;#需要压缩的文件类型gzip_types text/plain text/css text/xml text/javascript application/javascript application/json application/xml+rss application/rss+xml application/atom+xml image/svg+xml;#静态资源缓存open_file_cache max=20480 inactive=20s;open_file_cache_min_uses 1;open_file_cache_valid 30s;open_file_cache_errors on;reset_timedout_connection on;client_body_timeout 20;send_timeout 2;proxy_buffer_size 128k;proxy_buffers 32 128k;proxy_busy_buffers_size 128k;#Http强制重定向到Httpsserver {listen 80;server_name www.zuikakuedu.top;rewrite ^(.*)$ https://$host$1 permanent;}server {listen 443 ssl;server_name www.zuikakuedu.top;ssl_certificate /home/admin/ssl/5087465_www.zuikakuedu.top.pem;ssl_certificate_key /home/admin/ssl/5087465_www.zuikakuedu.top.key;ssl_session_cache shared:SSL:1m;ssl_session_timeout 5m;ssl_protocols TLSv1 TLSv1.1 TLSv1.2; #加密协议配置ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE; #加密套件配置ssl_prefer_server_ciphers on;#最咔酷线上课堂location / {proxy_pass https://localhost:9091/;proxy_set_header Host $host:$server_port;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;proxy_set_header X-Forwarded-Proto $scheme;proxy_set_header X-Forwarded-Port $server_port;proxy_set_header Connection "Upgrade";proxy_set_header Upgrade $http_upgrade;}#宝塔location /btSystem/ {proxy_pass http://localhost:8888/btSystem/;proxy_set_header Host $host:$server_port;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;proxy_set_header X-Forwarded-Proto $scheme;proxy_set_header X-Forwarded-Port $server_port;}#dockerlocation /docker/ {proxy_pass http://localhost:9000/;proxy_set_header Host $host:$server_port;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;proxy_set_header X-Forwarded-Proto $scheme;proxy_set_header X-Forwarded-Port $server_port;}#下载中心location /download/ {alias /home/admin/download/;autoindex on;autoindex_exact_size off;charset utf-8;}#通用错误页面配置(/usr/share/nginx/html/error.html)error_page 500 502 503 504 404 /error.html;location = /error.html {root html;charset utf-8;}}
}
更多教程,可见我的官方网站:最咔酷线上教程:www.zuikakuedu.cn
Nginx安装/负载均衡/反向代理配置与调优相关推荐
- Linux中 Nginx+uwsgi部署flask项目 Nginx负载均衡 反向代理
Nginx是一款自由的.开源的.高性能HTTP服务器和反向代理服务器. 轻量级,同样起web服务,比 apache占用更少的内存及资源 抗并发, nginx处理请求是异步非阻塞的,而 apache则是 ...
- day10 负载均衡反向代理
day10 负载均衡反向代理 1.复习 1.nginx+python的流程1.1安装基础环境yum install python3 pip3 install django==2.2.2安装uwsgi之 ...
- 架构之Nginx(负载均衡/反向代理)
Nginx ("engine x") 是一个高性能的 HTTP 和 反向代理 服务器 ,也是一个 IMAP/POP3/SMTP 代理 服务器 . Nginx 是由 Igor Sys ...
- Nginx安装手册,反向代理,负载均衡,keepalived高可用
Nginx安装手册 附件在下面 看附件中的 pdf 中的资料写的比较清晰: nginx安装环境 nginx是C语言开发,建议在linux上运行,本教程使用Centos6. ...
- Nginx学习总结(10)——Nginx前后端分离将多个请求转发到多个Tomcat,负载均衡反向代理
一.谈谈"渲染" 相信好多人都挺听过"渲染"这个词,但不清楚它是什么意思?前端开发以为这是后端的活儿,后端开发以为是前端的事儿,推着推着就不了了之.其实渲染很简 ...
- Nginx + Tomcat 负载均衡集群配置
摘要 Nginx ("engine x") 是一个高性能的 HTTP 和 反向代理 服务器,也是一个 IMAP/POP3/SMTP 代理服务器. Nginx 已经因为它的稳定性.丰 ...
- 负载均衡 反向代理为何叫反向代理?
转 https://www.zhihu.com/question/24723688 与正向代理比起来,反向代理是什么东西反向了? 关注者 1217 被浏览 184352 41 个回答 刘志军 公众号 ...
- 【Ngnix】可提供负载均衡反向代理的web服务器
前言 之前我们用IIS搭建的是web服务器即内网服务器,但通常不直接接受外网用户请求,由反向代理服务器充当这一衔接角色,用户直接访问反向代理服务器就可以获得目标服务器的资源.为提高网络吞吐和加强网络数 ...
- nginx 上传文件 405_今天教大家Nginx+tomcat负载均衡群集如何配置
实验环境如下 这里需要准备4台服务器(1台nginx.2台tomcat做负载.一台MySQL做数据存储) 准备软件包如下: nginx配置(172.16.1.54) 1.安装依赖包 yum -y in ...
最新文章
- 服务器php将视频转为m3u8,php应用ffmpeg对mp4文件转换并生成m3u8视频流文件
- 【TX2】英伟达Nvidia TX2连接蓝牙设备
- ecshop 2.7.x 去版权 lengze.com
- matplotlib 高阶之Transformations Tutorial
- 电子科技大学2019年计算机复试分数线,2019考研电子科技大学复试分数线已公布...
- Visual Sourcesafe Internet使用备忘
- matlab基础视频教程解压密码,价值上千元的MATLAB基础视频教程附源码请收下!
- PremierePR2019CC Beat Edit 安装好之后打不开?Pr下载模板安装后不能使用?Pr全屏预览?此效果需要GPU加速?小清新lut?
- 互联网金融反欺诈体系
- c语言 continue什么意思,continue在C语言中什么意思?
- Proximity indication
- 如何让文字变成语音?推荐三个免费把文字变成音频软件
- 内存走线 菊花链_[转帖]关于DDR4内存颗粒、单双面、主板布线和双通道的那些事儿...
- vue报错:the template root disallows ‘v-for‘ directives解决办法
- React生命周期理解
- 【软件】[Qt\C++] 使用qt c++写一个进程终结者程序 ——qt关闭外部进程
- 焊锡丝的含锡量越高越好吗?
- 【BZOJ2246】[SDOI2011]迷宫探险【搜索】【概率DP】
- Elasticsearch:使用最新的 Python client 8.0 来创建索引并搜索
- 004:Python语言元素之运算符