Nginx
1、Nginx 简介
1、什么是nginx
Nginx (“engine x”)是一个高性能的HTTP和反向代理web服务器,特点是占有内存少,并发能力强,事实上nginx的并发能力确实在同类型的网页服务器中表现较好。
Nginx专为性能优化而开发,性能是其最重要的考量,实现上非常注重效率,能经受高负载的考验,有报告表明能支持高达50000个并发连接数。
2、反向代理
a. 正向代理
在客户端(浏览器)配置代理服务器,通过代理服务器进行互联网访问。
b. 反向代理
反向代理,其实客户端对代理是无感知的,因为客户端不需要任何配置就可以访问,我们只需要将请求发送到反向代理服务器,由反向代理服务器去选择目标服务器,获取数据后,再返回给客户端。
此时反向代理服务器和目标服务器对外就是一个服务器,暴露的是代理服务器地址,隐藏了真实服务器IP地址。
3、负载均衡
单个服务器解决不了,我们增加服务器的数量,然后将请求分发到各个服务器上,将原先请求集中到单个服务器上的情况改为将请求分发到多个服务器上,将负载分发到不同的服务器,也就是我们所说的负载均衡。
4、动静分离
为了加快网站的解析速度,可以把动态页面和静态页面由不同的服务器来解析,加快解析速度。降低原来单个服务器的压力。
2、Nginx 安装
安装pcre
作用
PCRE(Perl Compatible Regular Expressions) 是一个Perl库,包括 perl 兼容的正则表达式库。nginx 的 http 模块使用 pcre 来解析正则表达式,所以需要在 linux 上安装 pcre 库,pcre-devel 是使用 pcre 开发的一个二次开发库。nginx也需要此库。
安装步骤
- 拷贝 pcre-8.37.tar.gz 文件到 /urs/src/ 目录下。
- tar -xvf pcre-8.37.tar.gz 解压得到 pcre-8.37 文件夹。
- 进入 pcre-8.37 文件夹,执行 ./configure 命令。
- 执行 make && make install 命令。
- 执行 pcre-config --version 命令,若输出版本号则安装成功。
安装其他依赖
yum -y install gcc zlib zlib-devel gcc-c++ libtool openssl openssl-devel
# 安装成功,输出信息
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
base | 3.6 kB 00:00
docker-ce-stable | 3.5 kB 00:00
epel | 4.7 kB 00:00
extras | 2.9 kB 00:00
updates | 2.9 kB 00:00
(1/4): extras/7/x86_64/primary_db | 205 kB 00:00
(2/4): epel/x86_64/updateinfo | 1.0 MB 00:00
(3/4): updates/7/x86_64/primary_db | 3.0 MB 00:00
(4/4): epel/x86_64/primary_db | 6.8 MB 00:00
Package gcc-4.8.5-39.el7.x86_64 already installed and latest version
Package zlib-1.2.7-18.el7.x86_64 already installed and latest version
Package zlib-devel-1.2.7-18.el7.x86_64 already installed and latest version
Package gcc-c++-4.8.5-39.el7.x86_64 already installed and latest version
Package libtool-2.4.2-22.el7_3.x86_64 already installed and latest version
Package 1:openssl-1.0.2k-19.el7.x86_64 already installed and latest version
Package 1:openssl-devel-1.0.2k-19.el7.x86_64 already installed and latest version
Nothing to do
安装Nginx
安装步骤
- 把 nginx-1.12.2.tar.gz 文件放到 /usr/src/ 路径下。
- tar -xvf nginx-1.12.2.tar.gz 解压上面的文件。(-x 解压 -v 显示详情 -f 指定解压缩文件)
- 进入nginx-1.12.2文件夹,执行 ./configure 命令。
- 执行 make && make install 命令。
- 进入 /usr/local/ 目录,若该目录下存在nginx文件夹则安装成功。
启动nginx
cd /usr/local/nginx/sbin
./nginx # 启动nginx
ps -ef | grep nginx # 查看有无nginx进程
查看配置文件
cd /usr/local/nginx/conf # 进入配置文件的文件夹
vim nginx.conf # 查看配置文件,可看到访问nginx的ip地址和端口号。
# =========================
server {
listen 80;
server_name localhost;
# =========================
# localhost:80 --> 可访问nginx.
遇到的问题
# 1. 启动服务失败。
[root@phliny sbin]# /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] still could not bind()
# 2.查看端口占用情况,nginx被占用了,不得不kill掉。
[root@phliny sbin]# ps -ef | grep nginx
root 1138 1 0 Jun09 ? 00:00:00 nginx: master process /www/server/nginx/sbin/nginx -c /www/server/nginx/conf/nginx.conf
www 1145 1138 0 Jun09 ? 00:00:00 nginx: worker process
www 1146 1138 0 Jun09 ? 00:00:13 nginx: cache manager process
root 3925 3051 0 17:52 pts/0 00:00:00 grep --color=auto nginx
root 3937 3051 0 17:52 pts/0 00:00:00 grep --color=auto nginx
# 3.杀掉占用的线程
[root@phliny sbin]# killall -9 nginx
# 4.重新启动nginx服务
cd /usr/local/nginx/sbin
./nginx # 启动nginx
# 5.重新查看进程,发现正常了。
ps -ef | grep nginx
root 3925 3051 0 17:52 pts/0 00:00:00 grep --color=auto nginx
root 4161 1 0 17:56 ? 00:00:00 nginx: master process ./nginx
nobody 4192 4161 0 17:57 ? 00:00:00 nginx: worker process
root 4332 3051 0 18:00 pts/0 00:00:00 grep --color=auto nginx
# 3. localhost:80也能正常访问nginx了。
3,Nginx常用命令
前提条件:必须要进入到nginx目录下( /usr/local/nginx/sbin )
cd /usr/local/nginx/sbin
./nginx -v # 查看nginx版本
./nginx # 直接启动nginx
./nginx -c /usr/local/nginx/conf/nginx.conf # 带上conf配置文件启动
./nginx -s stop # 关闭nginx
./nginx -s reload # 重新加载nginx
./nginx # 下面是直接启动显示的进程
ps -ef | grep nginx
root 3925 3051 0 17:52 pts/0 00:00:00 grep --color=auto nginx
root 4161 1 0 17:56 ? 00:00:00 nginx: master process ./nginx
nobody 4162 4161 0 17:56 ? 00:00:00 nginx: worker process
root 4170 3051 0 17:57 pts/0 00:00:00 grep --color=auto nginx
./nginx -c /usr/local/nginx/conf/nginx.conf # -c带上配置文件启动显示的进程
ps -ef | grep nginx
root 3925 3051 0 17:52 pts/0 00:00:00 grep --color=auto nginx
root 4625 1 0 18:05 ? 00:00:00 nginx: master process ./nginx -c /usr/local/nginx/conf/nginx.conf
nobody 4626 4625 0 18:05 ? 00:00:00 nginx: worker process
root 4631 3051 0 18:05 pts/0 00:00:00 grep --color=auto nginx
4,Nginx配置文件
cd /usr/local/nginx/conf/nginx.conf # 配置文件路径
# 1.全局块
#user nobody;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
# 2.events块
events {
worker_connections 1024;
}
# 3.http块
http {
# 4.http全局块
include mime.types;
default_type application/octet-stream;
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
#access_log logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
# 5.http srver块
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 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
# listen 8000;
# listen somename:8080;
# server_name somename alias another.alias;
# location / {
# root html;
# index index.html index.htm;
# }
#}
# HTTPS server
#
#server {
# listen 443 ssl;
# server_name localhost;
# ssl_certificate cert.pem;
# ssl_certificate_key cert.key;
# ssl_session_cache shared:SSL:1m;
# ssl_session_timeout 5m;
# ssl_ciphers HIGH:!aNULL:!MD5;
# ssl_prefer_server_ciphers on;
# location / {
# root html;
# index index.html index.htm;
# }
#}
}
配置文件中的内容
包含三部分内容
(1)全局块:配置服务器整体运行的配置指令
比如 worker_processes 1;处理并发数的配置
(2)events 块:影响 Nginx 服务器与用户的网络连接
比如 worker_connections 1024; 支持的最大连接数为 1024
(3)http 块
还包含两部分:
http 全局块
server 块
5,Nginx配置tomcat
安装配置步骤
-
卸载虚拟机中自带的java,安装从官网上下载下来的hotpot版本的jdk。
-
拉取 apache-tomcat-7.0.70.tar.gz 压缩包到 /usr/src 目录下。
-
使用 tar -xvf apache-tomcat-7.0.70.tar.gz 解压。
-
进入 /usr/src/apache-tomcat-7.0.70/bin 目录,使用 ./start.sh 命令开启tomcat。
-
tail -f /usr/src/apache-tomcat-7.0.70/logs/catalina.out 查看日志,启动成功。
[root@phliny apache-tomcat-7.0.70]# tail -f /usr/src/apache-tomcat-7.0.70/logs/catalina.out Jul 09, 2020 6:59:41 PM org.apache.catalina.startup.HostConfig deployDirectory INFO: Deploying web application directory /usr/src/apache-tomcat-7.0.70/webapps/ROOT Jul 09, 2020 6:59:41 PM org.apache.catalina.startup.HostConfig deployDirectory INFO: Deployment of web application directory /usr/src/apache-tomcat-7.0.70/webapps/ROOT has finished in 73 ms Jul 09, 2020 6:59:41 PM org.apache.coyote.AbstractProtocol start INFO: Starting ProtocolHandler ["http-bio-8080"] Jul 09, 2020 6:59:41 PM org.apache.coyote.AbstractProtocol start INFO: Starting ProtocolHandler ["ajp-bio-8009"] Jul 09, 2020 6:59:41 PM org.apache.catalina.startup.Catalina start INFO: Server startup in 1394 ms
-
浏览器输入 ip:8080 访问tomcat。
6,firewall
# 在 windows 系统中访问 linux 中 nginx,默认不能访问的,因为防火墙问题
#(1)关闭防火墙
#(2)开放访问nginx的端口号,80 端口
#(3)开放访问tomcat的端口号,80 端口
# (4) 或者在阿里云配置界面里面设置访问组
firewall-cmd --list-all # 查看开放的端口号
firewall-cmd --add-service=http –permanent
firewall-cmd --add-port=80/tcp --permanent # 设置nginx的端口号
firewall-cmd --add-port=8080/tcp --permanent # 设置tomcat的端口号
firewall-cmd –reload # 重启防火墙
systemctl restart firewalld.service
7,反向代理1
访问过程分析
具体配置
-
修改 C:\Windows\System32\drivers\etc 路径下的hosts文件。
120.xx.1xx.xxx www.123.com
-
cd /usr/local/nginx/conf 后,vim nginx.conf ,修改下面配置。
server { listen 80; server_name 120.24.144.249; # 访问120.24.144.249:80 将反向代理到下面的网址。 #charset koi8-r; #access_log logs/host.access.log main; location / { root html; # 配置反向代理的网址 proxy_pass http://127.0.0.1:8080; index index.html index.htm; }
-
访问 www.123.com 即可。
8,反向代理2
准备工作
-
先取消tomcat服务。
# 1.查看tomcat进程 ps -ef | grep tomcat root 7787 3051 0 19:08 pts/0 00:00:00 tail -f /usr/src/apache-tomcat-7.0.70/logs/catalina.out root 17638 1 0 22:28 pts/0 00:00:08 /usr/java/jdk1.8.0_251-amd64/bin/java -Djava.util.logging.config.file=/usr/src/apache-tomcat-7.0.70/conf/logging.properties -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djdk.tls.ephemeralDHKeySize=2048 -Djava.endorsed.dirs=/usr/src/apache-tomcat-7.0.70/endorsed -classpath /usr/src/apache-tomcat-7.0.70/bin/bootstrap.jar:/usr/src/apache-tomcat-7.0.70/bin/tomcat-juli.jar -Dcatalina.base=/usr/src/apache-tomcat-7.0.70 -Dcatalina.home=/usr/src/apache-tomcat-7.0.70 -Djava.io.tmpdir=/usr/src/apache-tomcat-7.0.70/temp org.apache.catalina.startup.Bootstrap start root 21363 11987 0 23:41 pts/1 00:00:00 grep --color=auto tomcat # 2.kill停掉tomcat进程 kill -9 17638 # 2.或者./shutdown.sh cd /usr/src/apache-tomcat-7.0.70/bin ./shutdown.sh
-
需要两台tomcat,默认的8080就使用 /usr/src/apache-tomcat-7.0.70 下的就好了。
-
新建一台tomcat,在 /usr/src 目录下,执行下面命令
mkdir tomcat8081 tar -zxvf apache-tomcat-7.0.70.tar.gz -C tomcat8081/ # 指定解压到新建的文件夹中
-
修改tomcat8081文件下新tomcat的配置
cd /usr/src/tomcat8081/apache-tomcat-7.0.70/conf vim server.xml # 修改8081tomcat中的端口号,防止和8080的冲突,下面为修改完成后的数据,为原数值+1。 # ------------------------ <Server port="8006" shutdown="SHUTDOWN"> <Connector port="8081" protocol="HTTP/1.1" .../> <Connector port="8010" protocol="AJP/1.3" redirectPort="8443" /> # ------------------------
-
防火墙开启8081端口,然后重启防火墙。
firewall-cmd --add-port=8081/tcp --permanent # 设置tomcat8081的端口号 firewall-cmd --add-port=8080/udp --permanent # 设置tomcat8081的端口号 systemctl restart firewalld.service # 重启防火墙,否则不生效。
-
执行两个tomcat的 ./startup.sh 命令,启动两台tomcat。
-
输出8080和8081网址测试。
-
8080:webapp下新建edu文件夹,创建a.html文件并输入测试内容,使用浏览器访问。
8081:webapp下新建vod文件夹,创建a.html文件并输入测试内容,使用浏览器访问。
nginx.conf配置文件
注意
/usr/local/nginx/conf(正确路径) --> /usr/src/nginx-1.12.2/conf (错误路径)
不要搞错了!!!!
配置
-
nginx.conf配置文件
server{ listen 9001; server_name 120.24.144.xxx; location ~ /edu/ { proxy_pass http://127.0.0.1:8080; } location ~ /vod/ { proxy_pass http://127.0.0.1:8081; } }
-
添加9001端口,重启防火墙。
-
访问 http://120.24.144.xxx:9001/vod/a.html 查看结果。
9,location 指令
该指令用于匹配 URL。
语法如下:
location [ = | ~ | ~* | ^~ ] uri {
}
1、= :用于不含正则表达式的 uri 前,要求请求字符串与 uri 严格匹配,如果匹配成功,就停止继续向下搜索并立即处理该请求。
2、~:用于表示 uri 包含正则表达式,并且区分大小写。
3、~*:用于表示 uri 包含正则表达式,并且不区分大小写。
4、^~:用于不含正则表达式的 uri 前,要求 Nginx 服务器找到标识 uri 和请求字符串匹配度最高的 location 后,立即使用此 location 处理请求,而不再使用 location 块中的正则 uri 和请求字符串做匹配。
注意:如果 uri 包含正则表达式,则必须要有 ~ 或者 ~* 标识。
10,负载均衡
步骤
-
8081 的webapps 新增 edu 文件夹,下面新增 a.html。
-
修改 nginx.conf 配置
http { .... # 1.设置 upstream myserver{ server 120.24.144.249:8080; server 120.24.144.249:8081; } server { listen 80; server_name 120.24.144.249; #charset koi8-r; #access_log logs/host.access.log main; location / { proxy_pass http://myserver; # 2.负载均衡 # proxy_pass http://127.0.0.1:8080; # 之前的反向代理。 root html; index index.html index.htm; } } }
-
重启 nginx 服务。
负载均衡的分配策略
upstream myserver{
[ ip_hash | fair ]
server 120.24.144.249:8080 [weight=10];
server 120.24.144.249:8081 [weight=5];
}
1、轮询(默认)
每个请求按时间顺序逐一分配到不同的后端服务器,如果后端服务器 down 掉,能自动剔除。
weight,ip_hash,fair都不写,就默认是轮询模式。
2、weight
weight 代表权,重默认为 1,权重越高被分配的客户端越多。
指定轮询几率,weight 和访问比率成正比,用于后端服务器性能不均的情况。
3、ip_hash
每个请求按访问 ip 的 hash 结果分配,这样每个访客固定访问一个后端服务器,可以解决 session 的问题。
4、fair
按后端服务器的响应时间来分配请求,响应时间短的优先分配。
11,动静分离
概念
使用 Nginx 处理静态页面,Tomcat 处理动态页面。动静分离从目前实现角度来讲大致分为两种,
一种是纯粹把静态文件独立成单独的域名,放在独立的服务器上,也是目前主流推崇的方案;
另外一种方法就是动态跟静态文件混合在一起发布,通过 nginx 来分开。
通过location指定不同的后缀名实现不同的请求转发。通过expires参数设置,可以使浏览器缓存过期时间,减少与服务器之前的请求和流量。具体Expires定义: 是给一个资源设定一个过期时间,也就是说无需去服务端验证,直接通过浏览器自身确认是否过期即可,所以不会产生额外的流量。此种方法非常适合不经常变动的资源。(如果经常更新的文件,不建议使用Expires来缓存),如果设置3d, 表示在这3天之内访问这个URL, 发送一个请求,比对服务器该文件最后更新时间没有变化,则不会从服务器抓取,返回状态码304,如果有修改,则直接从服务器重新下载,返回状态码200。
测试代码
-
根目录下创建 data 目录,data目录下创建 www 和 img 文件夹,分别存放 index.html 和 01.jpg。
-
配置nginx.conf文件。
server { listen 80; server_name 120.24.144.xxx; ... # 配置静态网页资源路径 location /www/ { root /data/; autoindex on; # 可显示目录。 } # 配置静态图片资源路径 location /img/ { root /data/; autoindex on; # 可显示目录。 }
-
重启 nginx 服务。
-
浏览器访问:http://120.24.144.xxx/www/index.html
12,Nginx高可用
什么是 nginx 高可用
(1)需要两台 nginx 服务器
(2)需要 keepalived
(3)需要虚拟 ip
准备工作
-
需要两台服务器 192.168.17.129 和 192.168.17.131
-
在两台服务器安装 nginx
-
在两台服务器安装 keepalived
- 使用 yum 命令进行安装
yum install keepalived –y - rpm -q -a keepalived 查看keepalived的版本号
- 安装之后,在 etc 里面生成目录 keepalived,有配置文件 keepalived.conf
- 使用 yum 命令进行安装
-
完成高可用配置(主从配置)
-
修改/etc/keepalived/keepalivec.conf 配置文件
global_defs { notification_email { acassen@firewall.loc failover@firewall.loc sysadmin@firewall.loc } notification_email_from Alexandre.Cassen@firewall.loc smtp_server 192.168.17.129 smtp_connect_timeout 30 router_id LVS_DEVEL } vrrp_script chk_http_port { script "/usr/local/src/nginx_check.sh" interval 2 #(检测脚本执行的间隔) weight 2 } vrrp_instance VI_1 { state BACKUP # 备份服务器上将 MASTER 改为 BACKUP interface ens33 # 网卡 ifconfig查看 virtual_router_id 51 # 主、备机的 virtual_router_id 必须相同 priority 90 # 主、备机取不同的优先级,主机值较大,备份机值较小 advert_int 1 authentication { auth_type PASS auth_pass 1111 } virtual_ipaddress { 192.168.17.50 # VRRP H 虚拟地址 } }
-
在/usr/local/src 添加检测脚本 nginx_check.sh
#!/bin/bash A=`ps -C nginx –no-header |wc -l` if [ $A -eq 0 ];then /usr/local/nginx/sbin/nginx sleep 2 if [ `ps -C nginx --no-header |wc -l` -eq 0 ];then killall keepalived fi fi
-
把两台服务器上 nginx 和 keepalived 启动
启动 nginx:./nginx
启动 keepalived:systemctl start keepalived.service
-
-
测试
在浏览器地址栏输入 虚拟 ip 地址 192.168.17.50;
把主服务器(192.168.17.129)nginx 和 keepalived 停止,再输入 192.168.17.50。
13,Nginx原理解析
1、master和worker
ps -ef | grep nginx
root 7308 1 0 16:17 ? 00:00:00 nginx: master process ./nginx
nobody 7309 7308 0 16:17 ? 00:00:00 nginx: worker process
root 7501 3379 0 16:20 pts/2 00:00:00 vim nginx.conf
root 11348 3401 0 17:38 pts/3 00:00:00 grep --color=auto nginx
2、worker如何进行工作的
3、一个master和多个woker的好处
- 可以使用 nginx –s reload 热部署,利用 nginx 进行热部署操作。
- 每个 woker 是独立的进程,如果有其中的一个 woker 出现问题,其他 woker 独立的,
继续进行争抢,实现请求过程,不会造成服务中断。
4、设置多少个woker合适
worker 数和服务器的 cpu 数相等是最为适宜的。
5、连接数 worker_connection
第一个:发送请求,占用了 woker 的几个连接数?
答案:2 或者 4 个。
第二个:nginx 有一个 master,有四个 woker,每个 woker 支持最大的连接数 1024,支持的
最大并发数是多少?
- 普通的静态访问最大并发数是: worker_connections * worker_processes /2 ;
- 而如果是 HTTP 作 为反向代理来说,最大并发数量应该是 worker_connections *
worker_processes/4 。