Nginx
什么是Nginx
- 高性能Http和反向代理服务。
- 提供IMAP/POP3/SMTP
- 占用内存少,并发能力强
- 专门为性能优化开发
- 支持高达5w并发连接
- 支持热部署
- 采用master-slave模型,减少IO
- https://lnmp.org/nginx.html
反向代理
正向代理(路由)
不能访问A网站,则通过B网站访问A网站。
反向代理
分流,客户端向代理服务器发送请求,代理服务器将请求发送给目标服务器。
负载均衡
通过代理服务器将多个请求均分到不同服务器中
动静分离
不同服务器对动态文件和静态文件进行拆分响应,实现动静分离。
使用
nginx安装
# 安装依赖
yum -y install make zlib zlib-devel gcc-c++ libtool openssl openssl-devel
# 下载nginx
wget http://nginx.org/download/nginx-1.21.3.tar.gz
# 解压nginx
tar -xvf nginx-1.21.3.tar.gz
# 检查
./configure
# 安装
make && make install
# 检查安装成功
cd /usr/local/nginx/sbin
# 存在nginx即可
./nginx # 启动nginx
端口配置
/usr/local/nginx/conf/nginx.conf
http:server:listen
常用命令
#防火墙端口列表
firewall-cmd --list-all
#开放端口
firewall-cmd --add-service=http --permanent
sudo firewall-cmd --add-port=80/tcp --permanent
# 重启防火墙
firewall-cmd --reload
# 关闭nginx
./nginx -s stop
# 重启nginx
./nginx -s reload
配置文件
配置文件地址:/usr/local/nginx/conf/nginx.conf
# 全局配置
#user nobody;
# 处理并发数
worker_processes 1;
#pid logs/nginx.pid;
# events配置
events {
# 最大连接数
worker_connections 1024;
}
# http配置
http {
include mime.types;
default_type application/octet-stream;
#access_log logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
# 虚拟主机
server {
# 监听端口
listen 80;
# 主机名
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
#路径配置
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
反向代理
server {
listen 80;
server_name www.sina.com;
location / {
proxy_pass http://tomcat1;
#配置默认访问页,这里就会访问到tomcat1里面的那个index.jsp文件里面
index index.jsp;
}
}
#配置www.houhu.com:80对应的服务器监听端口
upstream tomcat2 {
server 47.91.248.236:8082;
}
server {
listen 80;
server_name www.houhu.com;
location / {
proxy_pass http://tomcat2;
#配置默认访问页,这里就会访问到tomcat2里面的那个index.jsp文件里面
index index.jsp;
}
}
负载均衡
#动态服务器组 轮训
upstream dynamic_zuoyu {
server localhost:8080; #tomcat 7.0
server localhost:8081; #tomcat 8.0
server localhost:8082; #tomcat 8.5
server localhost:8083; #tomcat 9.0
}
#动态服务器组 权重配置
upstream dynamic_zuoyu {
server localhost:8080 weight=2; #tomcat 7.0
server localhost:8081; #tomcat 8.0
server localhost:8082 backup; #tomcat 8.5
server localhost:8083 max_fails=3 fail_timeout=20s; #tomcat 9.0
}
#动态服务器组 IPhash 解决跨域问题
upstream dynamic_zuoyu {
ip_hash; #保证每个访客固定访问一个后端服务器
server localhost:8080 weight=2; #tomcat 7.0
server localhost:8081; #tomcat 8.0
server localhost:8082; #tomcat 8.5
server localhost:8083 max_fails=3 fail_timeout=20s; #tomcat 9.0
}
#动态服务器组
upstream dynamic_zuoyu {
least_conn; #把请求转发给连接数较少的后端服务器
server localhost:8080 weight=2; #tomcat 7.0
server localhost:8081; #tomcat 8.0
server localhost:8082 backup; #tomcat 8.5
server localhost:8083 max_fails=3 fail_timeout=20s; #tomcat 9.0
}
#其他页面反向代理到tomcat容器
location ~ .*$ {
index index.jsp index.html;
proxy_pass http://dynamic_zuoyu;
}