第一章 初识nginx

2020-03-17  本文已影响0人  Daisy小朋友
一 nginx的三个主要应用场景
image.png

web请求通过红色箭头访问进来,访问nginx之后访问后端的应用服务(tomcat等)再去访问数据库(Mysql,redis),提供基本的应用服务。

反向代理服务:这里有一个问题,应用服务开发效率高,所以运行效率低,QPS,TPS,并发都是受限制的,所以就有需要把它们组成集群,提供高可用,也需要nginx具有反向代理功能,动态请求转给应用服务,构成集群,也就涉及到动态扩容和冗灾,反向代理也必须具备负载均衡能力。

随着网络链路的增长,用户体验到的时延也会增多,所以如果我们能把一些所有用户看起来不变的或者在一段时间内看起来不变的动态内容缓存到nginx部分,由nginx直接向用户提供,可以减少时延,所以反向代理也引出另一个功能叫缓存,加速我们的访问。

静态资源服务:很多时候我们在访问css,javascript或者像一些小图片这样的静态资源是没有必要由应用服务来访问的,它只需要通过本地文件,系统上放置的静态资源,直接由nginx提供访问,nginx的静态资源功能。

API服务:应用服务性能有很多的问题,但是数据库服务要比应用服务好的多,因为它的业务场景比较简单,并发性能和TPS都要高于应用服务,所以引申第三个服务,由nginx直接去访问数据库,mysql,redis,利用nginx强大的并发能力提供,如OpenResty

二 nginx出现的原因
三 nginx优点
四 nginx组成
五 nginx发行版本
六 编译nginx

第三方模块需要编译才可以

需要安装依赖包:yum -y install pcre-devel openssl openssl-devel  gcc-c++

在vim中修改nginx配置与法

mkdir ~/.vim

cp -r contrib/vim/* ~/.vim/

查看帮助文档

cd man

man ./nginx.8

查看nginx编译支持的参数

./configure --help |more

编译

./configure —prefix=/data

make&&make install 
七 nginx语法配置
image.png
八 nginx命令行
image.png

热部署:平滑升级nginx


*   下载最新版本并通过查看nginx -V在新版本中编译相同的模块,之后make,但是不要执行make install

*   重命名低版本二进制文件 cp ningx nginx.old

*   重新copy新版本的二进制文件 cp /root/nginx-1.15.8/objs/nginx .

*   ps -ef|grep nginx 查看master的进程id

*   kill -USR2 3798(master进程id)旧的master进程会将自己改为.oldbin,然后执行新版nginx,新旧同时运行

*   kill -WINCH 6651(worker进程id) 逐步停止旧版本worker

*   查看版本信息并验证是否正常
问题处理:

如果新master运行没问题:

可以执行kill -QUIT old-nginx-master-pid把老master进程杀掉。

如果新master运行有问题,需要版本回退:

执行kill -HUP old-nginx-master-pid把老master reload了(不能用nginx -s reload,因为当前的nginx二进制文件已经是新的,不会对老的nginx起作用),这时候老master会起来自己的worker进程,但是老worker进程不会监听80或443端口,必须执行kill -WINCH new-nginx-master-pid(使新master结束自己的worker进程)后,老worker进程才会监听80端口,接收新情求。

作者回复: reload新启的老worker在启动后就会监听端口处理请求。可以用access日志看下,其中每条access日志上输出进程id。

nginx信号控制

HUP:重启

QUIT:从容关闭

INT:从容关闭

TERM:快速关闭

USER1:切换日志文件 对应reopen命令

-- kill -USER1 进程号

USER2:平滑升级可执行进程

-- kill -USER2 进程号 WINCH:从容关闭工作进程

-- kill -WINCH 主进程号

日志切割

第一种,重命名日志后,./nginx -s reopen 应该把cp命令改为mv命令,因为linux文件系统中,改名并不会影响已经打开文件的写入操作,内核inode不变,这样就不会出现丢日志了

第二种,脚本切割,写到crontab中

第三种,只要mv后再reopen就可以的或者logrotate切割

第四种,提供重新打开日志 不会丢日志方式

#!/bin/bash

#设置日志文件存放目录

logs_path="/alidata/log/nginx/access/"

DAYS=30

#设置pid文件

pid_path="/alidata/server/nginx/logs/nginx.pid"

#重命名日志文件

mv ${logs_path}default.log ${logs_path}default-access_$(date -d "yesterday" +"%Y%m%d").log

#向nginx主进程发信号重新打开日志

kill -USR1 `cat ${pid_path}`

find ${logs_path} -name "default-access_*.log" -type f -mtime +$DAYS -exec rm {} \;
第五种, image.png
九 用ngnx搭建一个可用的静态资源web服务器
image.png
使用root会把url中的一些路径带到文件目录中,所以通常使用alias,
别名alias直接指到workpress/目录下, 与文件目录路径与url路径是一一对应的
配置展示目录结构: image.png image.png
  gzip  on;  ##打开gzip压缩

  gzip_min_length 1;  ##表示小于1字节的就不需要压缩了

  gzip_comp_level 2;  ##表示压缩级别为2

  gzip_types  ##表示压缩的类型

http://nginx.org/en/docs/http/ngx_http_core_module.html#limit_rate

image.png
set $limit_rate 1k; 每秒传输1k字节到浏览器中。限制访问速度,公网带宽时非常有限的,当有许多并发用户使用我们的带宽时会形成一个争抢关系,我们可能会为了让用户访问某些大文件的时候限制它的速度期望能够分配足够的带宽给必要的小文件,如css,jss等,可以使用set命令+内置变量,限制nginx向客户浏览器发送的一个速度。

http://nginx.org/en/docs/http/ngx_http_core_module.html#variables

image.png image.png

log_format日志格式定义,main代表域名,后面是变量。打开server下的access log表示访问这个server的日志均会被记录在daisy.access.log中,格式是域名为main的

十 用nginx搭建一个具备缓存功能的反向代理服务

上游服务器一般是不提供公网访问的,下面在一台机器上举例

静态服务器修改为: image.png

重启

代理服务器(openresty):增加 image.png 命名为local image.png
并将80所有的请求都转到proxy_pass [http://local](http://local/)中

 proxy_set_header Host $host;    ##远端host

 proxy_set_header X-Real-IP $remote_addr;  ##反向代理与tcp链接,反向代理与上游服务器都是一条连接,X-Real-IP代表客户端或上一级代理IP

 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;##X-Forwarded-For包含了客户端和各级代理ip的完整ip链路

proxy_set_header请参考[https://www.cnblogs.com/yanghj010/p/5980974.html](https://www.cnblogs.com/yanghj010/p/5980974.html)

缓存功能: 缓存只用于反向代理。必须上游响应符合缓存条件才会存储到该目录

nginx作为反向代理时,动态的请求:不同的用户访问同一个url访问的内容是不同的,这个时候会交由上游服务器处理,但是有些内容一段时间是不会发生变化的,为了减少上游服务器的压力,nginx缓存上游服务器的内容,比如缓存一天,一天内只取缓存的内容。nginx性能高于上游服务器的性能,对于一些小型站点,此配置会提升性能。
image.png

http中

proxy_cache_path /tmp/nginxcache  #缓存路径

levels=1:2   #缓存空间有两层hash目录

keys_zone=my_cache:10m  #缓存区名称和缓存空间大小

max_size=10g  #硬盘缓存空间大小

inactive=60m   #设置多长时间没有被访问将删除

use_temp_path=off;
image.png

server中

proxy_cache_key   # 用户的变量

proxy_cache_valid  ##对于那些相应不返回
十一 用goaccess实现可视化并实时监控access日志

安装goaccess:https://goaccess.io/download

yum install goaccess

报错:Missing development files for the GeoIP library

解决:yum install GeoIP-devel

报错:configure: error: *** Missing development libraries for ncursesw

解决:sudo yum install ncurses-devel

[https://goaccess.io/get-started](https://goaccess.io/get-started)  官网

[https://www.fanhaobai.com/2017/06/go-access.html](https://www.fanhaobai.com/2017/06/go-access.html)  参考

使用:

goaccess access.log -o report.html --log-format=COMBINED  用于分析网站数据

goaccess access.log -o ../html/report.html --real-time-html --time-format='%H:%M:%S' --date-format='%d/%b/%Y' --log-format=COMBINED

nginx中配置访问report.html 可实时访问access统计数据,但是5p测试环境不生效不知道为什么-应该是公有云机器的7890端口没开(默认goaccess在开启实时real-time-html后会监听端口7890的websocket,如果服务器不允许请求7890端口,你就看不到那个页面是实时更新的——你会发现访问的页面最后更新时间始终不变。这一点人很多忽略了,很多人以为是哪个生成html静态文件是实时更新的,其实根本不是,那个文件本身一旦生成就不动了,真正更新的实时内容是从websocket过来的)

Q:如果做了每天的日志切割,再使用GoAccess 是不是就意味着只能看到当天的统计结果

A:不会的,GoAccess会在内存中缓存运行以来的日志分析结果

如果你把goaccess与nginx部署在一起,那么goaccess会争抢cpu和内存。https://goaccess.io/faq这个页面里有goaccess的资源消耗benchmark数据,请参考。

Q:同一个站点部署在多个服务器上,goaccess针对多台服务器上的nginx日志文件能做统一采集和展示吗?

A:1 可以用syslog协议把多台server的日志写到一台日志server上,这样可以提高性能,因为少了本地磁盘IO

       2 用NFS把多台主机的日志目录映射在一起,用goaccess再分析
十二 从网络原理开看SSL安全协议

对称加密和非对称加密
证书公信力
网络安全:大部分站点都是通过https来实现自己的数据安全的。
了解https:https://www.jianshu.com/p/650ad90bf563

image.png

应用---- >http层

Q: ssl第一次握手还是明文传输,也不安全,现在提了一个hsts是什么

A: ssl第一次握手是明文传输,但它只是传输安全套件以及公钥,之后数据是用新生成的对称密钥加密过的,所以SSL是安全的。hsts主要应用在浏览器端,它是强制浏览器使用https方式,对nginx来说,只需要在返回的http头部上添加Strict-Transport-Security,告诉浏览器这个站点只能通过https访问即可。

image.png image.png image.png
十三 SSL协议握手时nginx的性能瓶颈在哪里

TLS通讯主要做两件事(消耗性能):交换密钥和加密数据

image.png

如果是小文件比较多——考验非对称加密性能
大文件比较多——考验对称加密算法性能

十四 用免费ssl证书实现一个https站点

安装

yum install python2-certbot-nginx 
如果安装过程中报错:
报错1:
error: unpacking of archive failed on file /usr/lib/python2.7/site-packages/urllib3/packages/ssl_match_hostname: cpio: rename
解决1:
PIP已经安装了对应的版本包,此时yum安装的rpm包与pip里的冲突,先把pip里的包卸载掉再用yum 重新安装
[root@compute01 home]# pip freeze|grep urllib3
You are using pip version 9.0.1, however version 10.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
urllib3==1.22
[root@compute01 home]# pip uninstall urllib3
[root@compute01 home]# yum install python-urllib3
参考:[https://blog.csdn.net/weixin_34199405/article/details/91949454](https://blog.csdn.net/weixin_34199405/article/details/91949454)
报错2:
The nginx plugin is not working; there may be problems with your existing configuration.
The error was: PluginError('Nginx build is missing SSL module (--with-http_ssl_module).',)
解决2:
为nginx安装ssl模块

生成证书

certbot --nginx --nginx-server-root=/data/nginx/conf -d git.chang.pub
过程
[root@izshvqfkb75a89z ~]# certbot --nginx --nginx-server-root=/data/nginx/conf -d git.chang.pub
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator nginx, Installer nginx
Enter email address (used for urgent renewal and security notices) (Enter 'c' to
cancel): 15032180966@163.com
Starting new HTTPS connection (1): acme-v02.api.letsencrypt.org

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Please read the Terms of Service at
https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf. You must
agree in order to register with the ACME server at
https://acme-v02.api.letsencrypt.org/directory
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(A)gree/(C)ancel: A

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Would you be willing to share your email address with the Electronic Frontier
Foundation, a founding partner of the Let's Encrypt project and the non-profit
organization that develops Certbot? We'd like to send you email about our work
encrypting the web, EFF news, campaigns, and ways to support digital freedom.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Y)es/(N)o: n
Obtaining a new certificate
Performing the following challenges:
http-01 challenge for git.chang.pub
Waiting for verification...
Cleaning up challenges
Deploying Certificate to VirtualHost /data/nginx/conf/conf.d/git.conf

Please choose whether or not to redirect HTTP traffic to HTTPS, removing HTTP access.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1: No redirect - Make no further changes to the webserver configuration.
2: Redirect - Make all requests redirect to secure HTTPS access. Choose this for
new sites, or if you're confident your site works on HTTPS. You can undo this
change by editing your web server's configuration.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Select the appropriate number [1-2] then [enter] (press 'c' to cancel): 1
这块含义是需不需要设置重定向,2的话不安全的httpd跳转到https
Future versions of Certbot will automatically configure the webserver so that all requests redirect to secure HTTPS access. You can control this behavior and disable this warning with the --redirect and --no-redirect flags.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Congratulations! You have successfully enabled https://git.chang.pub

You should test your configuration at:
https://www.ssllabs.com/ssltest/analyze.html?d=git.chang.pub
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

IMPORTANT NOTES:
 - Congratulations! Your certificate and chain have been saved at:
   /etc/letsencrypt/live/git.chang.pub/fullchain.pem
   Your key file has been saved at:
   /etc/letsencrypt/live/git.chang.pub/privkey.pem
   Your cert will expire on 2020-06-15. To obtain a new or tweaked
   version of this certificate in the future, simply run certbot again
   with the "certonly" option. To non-interactively renew *all* of
   your certificates, run "certbot renew"
 - Your account credentials have been saved in your Certbot
   configuration directory at /etc/letsencrypt. You should make a
   secure backup of this folder now. This configuration directory will
   also contain certificates and private keys obtained by Certbot so
   making regular backups of this folder is ideal.
 - If you like Certbot, please consider supporting our work by:

   Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
   Donating to EFF:                    https://eff.org/donate-le

注意点:

1 nginx编译时需要启用ssl模块
2 域名需要注册,必须CA机构也能访问这个域名,如果你自建域名服务,CA机构访问不了,DV证书是不会颁发的
3 这个https和付费的https有什么差异呢
付费的https也分DV证书、OV证书和EV证书。从安全传输这个角度来说,这三种证书效果一样。从浏览器对证书的认可上来,DV证书最差。如果你买的是付费的DV证书,跟这里的例子都一样,因为主流的浏览器都认Lets encrypt
4 证书只有4个月有效期
5 生成完毕后直接访问https不生效
解决:重启nginx,将443端口启动

域名到期脚本自动续期参考:

参考:https://zning.me/15424636102403.html
https://certbot.eff.org/lets-encrypt/centosrhel7-nginx
https://certbot.eff.org/docs/install.html

上一篇 下一篇

猜你喜欢

热点阅读