Nginx学习笔记

Nginx学习笔记

简介

Nginx (engine x) 是一个高性能的HTTP反向代理web服务器,同时也提供了IMAP/POP3/SMTP服务。Nginx是由伊戈尔·赛索耶夫为俄罗斯访问量第二的Rambler.ru站点(俄文:Рамблер)开发的,第一个公开版本0.1.0发布于2004年10月4日。

其将源代码以类BSD许可证的形式发布,因它的稳定性、丰富的功能集、简单的配置文件和低系统资源的消耗而闻名。2011年6月1日,nginx 1.0.4发布。

Nginx是一款轻量级Web 服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器,在BSD-like 协议下发行。其特点是占有内存少,并发能力强,事实上nginx的并发能力在同类型的网页服务器中表现较好,中国大陆使用nginx网站用户有:百度、京东新浪网易腾讯淘宝等。

安装

下载nginx安装包

地址:https://nginx.org/en/download.html

下载名为nginx-*.tar.gz的安装包

在linux下安装nginx光有这个包还是不够的,还需要以下linux系统软件才能完整的安装

安装所需依赖

  • pcre

    下载pcre安装包

    wget https://jaist.dl.sourceforge.net/project/pcre/pcre/8.45/pcre-8.45.tar.gz
    

    安装

    1. 将下载好的安装包复制到 /usr/src目录下

    2. 解压pcre

      root@server-01:/usr/src# tar -vxf pcre-8.45.tar.gz
      
    3. 进入解压后的pcre目录执行./configure

      刚安装的linux系统可能不带gcc,执行上面的命令的时候可能会报如下的错误 configure: error: no acceptable C compiler found in $PATH执行 apt install gcc安装成功后重新执行./configure 即可也可能会出现如下错误:config.status: error: Something went wrong bootstrapping makefile fragments    for automatic dependency tracking. If GNU make was not used, consider   re-running the configure script with MAKE=“gmake” (or whatever is   necessary). You can also try re-running configure with the    ‘–disable-dependency-tracking’ option to at least be able to build   the package (albeit without support for automatic dependency tracking).See `config.log’ for more details在执行./configure命令的时候附加"–disable-dependency-tracking"参数即可

    4. 编译

      执行make && make install编译pcre

      期间可能出现如下报错:

      Command 'make' not found, but can be installed with:
      
      apt install make        # version 4.2.1-1.2, or
      apt install make-guile  # version 4.2.1-1.2
      
      

      执行apt install makeapt install make-guile安装这两个make执行所需依赖后,重新执行make && make install

解压安装

  1. 将nginx压缩包复制到/usr/src目录下

  2. 解压安装包root@server-01:/usr/src# tar -vxf nginx-1.20.1.tar.gz

  3. 进入解压缩目录执行root@server-01:/usr/src/nginx-1.20.1# ./configure

    期间可能出现如下报错

    ./configure: error: the HTTP rewrite module requires the PCRE library.
    You can either disable the module by using --without-http_rewrite_module
    option, or install the PCRE library into the system, or build the PCRE library
    statically from the source with nginx by using --with-pcre=<path> option.
    

    使用whereis pcre查找到pcre的目录,(如果没有找到,则回到pcre安装步骤)并重新执行./configure命令,同时附带’–with-pcre’参数

    root@server-01:/usr/src/nginx-1.20.1# whereis pcre
    pcre: /usr/src/pcre-8.45/pcre.h
    root@server-01:/usr/src/nginx-1.20.1# ./configure --with-pcre=/usr/src/pcre-8.45/
    

    期间还可能遇到如下错误

    ./configure: error: the HTTP gzip module requires the zlib library.
    You can either disable the module by using --without-http_gzip_module
    option, or install the zlib library into the system, or build the zlib library
    statically from the source with nginx by using --with-zlib=<path> option.
    

    执行apt install zlib1gapt install zlib1g-dev安装zlib(在ubuntu软件源里zlib和zlib-devel叫做zlib1g zlib1g.dev)

    安装完后重新执行./configure --with-pcre=/usr/src/pcre-8.45/

    安装结果如下,则代表nginx配置成功

    Configuration summary
      + using system PCRE library
      + OpenSSL library is not used
      + using system zlib library
    
      nginx path prefix: "/usr/local/nginx"
      nginx binary file: "/usr/local/nginx/sbin/nginx"
      nginx modules path: "/usr/local/nginx/modules"
      nginx configuration prefix: "/usr/local/nginx/conf"
      nginx configuration file: "/usr/local/nginx/conf/nginx.conf"
      nginx pid file: "/usr/local/nginx/logs/nginx.pid"
      nginx error log file: "/usr/local/nginx/logs/error.log"
      nginx http access log file: "/usr/local/nginx/logs/access.log"
      nginx http client request body temporary files: "client_body_temp"
      nginx http proxy temporary files: "proxy_temp"
      nginx http fastcgi temporary files: "fastcgi_temp"
      nginx http uwsgi temporary files: "uwsgi_temp"
      nginx http scgi temporary files: "scgi_temp"
    
    
  4. 编译源码

    在nginx解压缩目录执行make && make install编译源码,编译执行成功后,会在/usr/local/nginx创建一个nginx目录,nginx的执行程序就在该目录中

使用

查看版本

进入/usr/local/nginx/sbin目录

执行./nginx -V查看nginx版本

root@server-01:/usr/local/nginx/sbin# ./nginx -V
nginx version: nginx/1.20.1
built by gcc 9.3.0 (Ubuntu 9.3.0-17ubuntu1~20.04)
configure arguments:

启动

进入/usr/local/nginx/sbin目录

执行./nginx便可启动nginx服务

期间可能出现如下报错:问题可能是pcre安装有问题,导致nginx指向pcre的软链有问题

root@server-01:/usr/local/nginx/sbin# ./nginx
./nginx: error while loading shared libraries: libpcre.so.1: cannot open shared object file: No such file or directory

在安装完pcre后,我们执行如下命令find / -type f -name *libpcre.so.*

root@server-01:/usr/local/nginx/sbin# find / -type f -name *libpcre.so.*
/snap/core20/1169/usr/lib/x86_64-linux-gnu/libpcre.so.3.13.3
/snap/core18/2128/lib/x86_64-linux-gnu/libpcre.so.3.13.3
/usr/local/lib/libpcre.so.1.2.13
/usr/src/pcre-8.45/.libs/libpcre.so.1.2.13
/usr/lib/x86_64-linux-gnu/libpcre.so.3.13.3

再执行ln -s /usr/lib/x86_64-linux-gnu/libpcre.so.3.13.3 /usr/lib/x86_64-linux-gnu/libpcre.so.1

此时,我们将/usr/lib/x86_64-linux-gnu/libpcre.so.3.13.3软链到/usr/lib/x86_64-linux-gnu/目录下的libpcre.so.1文件

执行完以上操作后,重新执行./nginx便可成功启动服务

使用ps -ef|grep nginx查看进程信息

关闭

执行/usr/local/nginx/sbin/nginx -s stop即可关闭服务

root@server-01:/usr/local/nginx/sbin# ps -ef|grep nginx
root       23476       1  0 13:15 ?        00:00:00 nginx: master process ./nginx
nobody     23477   23476  0 13:15 ?        00:00:00 nginx: worker process
root       27008    6547  0 13:41 pts/0    00:00:00 grep --color=auto nginx
root@server-01:/usr/local/nginx/sbin# ./nginx -s stop
root@server-01:/usr/local/nginx/sbin# ps -ef|grep nginx
root       27015    6547  0 13:41 pts/0    00:00:00 grep --color=auto nginx

重新加载

在修改完nginx配置文件后,执行./nginx -s reload 便可以不用停止服务,重新加载配置文件

配置

nginx的配置文件位于/usr/local/nginx/conf/nginx.conf中,以下为默认配置

#指令名    指令值;  #全局块,主要设置Nginx服务器整体运行的配置指令
worker_processes  1;

#events块,主要设置,Nginx服务器与用户的网络连接,这一部分对Nginx服务器的性能影响较大
events {
    worker_connections  1024;
}

#http块,是Nginx服务器配置中的重要部分,代理、缓存、日志记录、第三方模块配置...
http {

        #指令名    指令值;
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;

        #server块,是Nginx配置和虚拟主机相关的内容
    server {
        listen       80;
        server_name  localhost;

        #location块,基于Nginx服务器接收请求字符串与location后面的值进行匹配,对特定请求进行处理
        location / {

                #指令名    指令值;
            root   html;
            index  index.html index.htm;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }

}

通过上面的配置文件,我们可以知道,该配置文件由三部分组成:全局块events块http块

全局块

  • user

用于配置运行Nginx服务器的worker进程的用户和用户组。

名称
语法 user user [group]
默认值 nobody

该属性也可以在编译的时候指定,语法如下./configure --user=user --group=group,如果两个地方都进行了设置,最终生效的是配置文件中的配置。

例子:

设置一个用户信息"www"

user www;
  • master_process

用来指定是否开启工作进程

名称
语法 master_process on/off;
默认值 master_process on;
  • worker_processes

用于配置Nginx生成工作进程的数量,这个是Nginx服务器实现并发处理服务的关键所在。理论上来说workder process的值越大,可以支持的并发处理量也越多,但事实上这个值的设定是需要受到来自服务器自身的限制,建议将该值和服务器CPU的内核数保存一致。

名称
语法 worker_processes num/auto;
默认值 1

当我们把该值设置成3后

worker_processes  3;

重新加载nginx配置文件,查看进程信息

root@server-01:/usr/local/nginx/sbin# ps -ef|grep nginx
root       27885       1  0 14:10 ?        00:00:00 nginx: master process ./nginx
nobody     27886   27885  0 14:10 ?        00:00:00 nginx: worker process
root       27888    6547  0 14:10 pts/0    00:00:00 grep --color=auto nginx
root@server-01:/usr/local/nginx/sbin# cd ../conf/
root@server-01:/usr/local/nginx/conf# vim nginx.conf
root@server-01:/usr/local/nginx/conf# vim nginx.conf
root@server-01:/usr/local/nginx/conf# cd ../sbin/nginx -s reload
-bash: cd: too many arguments
root@server-01:/usr/local/nginx/conf# ../sbin/nginx -s reload
root@server-01:/usr/local/nginx/conf# ps -ef|grep nginx
root       27885       1  0 14:10 ?        00:00:00 nginx: master process ./nginx
nobody     27966   27885  0 14:12 ?        00:00:00 nginx: worker process
nobody     27967   27885  0 14:12 ?        00:00:00 nginx: worker process
nobody     27968   27885  0 14:12 ?        00:00:00 nginx: worker process
root       27972    6547  0 14:12 pts/0    00:00:00 grep --color=auto nginx

我们可以看到默认的worker_processes 为1的时候,就只有worker process一个进程,当我们把它修改成3以后,就多了三个worker process

  • daemon

设定Nginx是否以守护进程的方式启动,守护式进程是linux后台执行的一种服务进程,特点是独立于控制终端,不会随着终端关闭而停止。

名称
语法 daemon on/off;
默认值 daemon on;
  • pid

用来配置Nginx当前master进程的进程号ID存储的文件路径。

名称
语法 pid file;
默认值 默认为:/usr/local/nginx/logs/nginx.pid

该属性可以通过./configure --pid-path=PATH来指定

  • error_log

用来配置Nginx的错误日志存放路径

名称
语法 error_log file [日志级别];
默认值 error_log logs/error.log error;
位置 全局块、http、server、location

该属性可以通过./configure --error-log-path=PATH来指定

其中日志级别的值有:debug|info|notice|warn|error|crit|alert|emerg,翻译过来为试|信息|通知|警告|错误|临界|警报|紧急,这块建议大家设置的时候不要设置成info以下的等级,因为会带来大量的磁盘I/O消耗,影响Nginx的性能。

  • include

用来引入其他配置文件,使Nginx的配置更加灵活

名称
语法 include file;
默认值

events块

  • accept_mutex

    用来设置Nginx网络连接序列化

名称
语法 accept_mutex on
默认值 accept_mutex on;
这个配置主要可以用来解决常说的"惊群"问题。大致意思是在某一个时刻,客户端发来一个请求连接,Nginx后台是以多进程的工作模式,也就是说有多个worker进程会被同时唤醒,但是最终只会有一个进程可以获取到连接,如果每次唤醒的进程数目太多,就会影响Nginx的整体性能。如果将上述值设置为on(开启状态),将会对多个Nginx进程接收连接进行序列号,一个个来唤醒接收,就防止了多个进程对连接的争抢。
  • multi_accept

    用来设置是否允许同时接收多个网络连接

名称
语法 multi_accept on
默认值 multi_accept off;
如果multi_accept被禁止了,nginx一个工作进程只能同时接受一个新的连接。否则,一个工作进程可以同时接受所有的新连接
  • worker_connections

    用来配置单个worker进程最大的连接数

名称
语法 worker_connections number;
默认值 worker_commections 512;
这里的连接数不仅仅包括和前端用户建立的连接数,而是包括所有可能的连接数。另外,number值不能大于操作系统支持打开的最大文件句柄数量。
  • use

    用来设置Nginx服务器选择哪种事件驱动来处理网络消息。

名称
语法 use method;
默认值 根据操作系统定
注意:此处所选择事件处理模型是Nginx优化部分的一个重要内容,method的可选值有select/poll/epoll/kqueue等,之前在准备centos环境的时候,我们强调过要使用linux内核在2.6以上,就是为了能使用epoll函数来优化Nginx。

另外这些值的选择,我们也可以在编译的时候使用

- `-with-select_module`、`-without-select_module`、
- `-with-poll_module`、`-without-poll_module`来设置是否需要将对应的事件驱动模块编译到Nginx的内核。

http块

  • 定义MIME-Type

    我们都知道浏览器中可以显示的内容有HTML、XML、GIF等种类繁多的文件、媒体等资源,浏览器为了区分这些资源,就需要使用MIME Type。所以说MIME Type是网络资源的媒体类型。Nginx作为web服务器,也需要能够识别前端请求的资源类型。

    在Nginx的配置文件中,默认有两行配置

    include mime.types;
    default_type application/octet-stream;
    

    default_type:用来配置Nginx响应前端请求默认的MIME类型。

名称
语法 default_type mime-type;
默认值 default_type text/plain;
位置 http、server、location

在default_type之前还有一句include mime.types,include之前我们已经介绍过,相当于把mime.types文件中MIMT类型与相关类型文件的文件后缀名的对应关系加入到当前的配置文件中。

举例来说明:

有些时候请求某些接口的时候需要返回指定的文本字符串或者json字符串,如果逻辑非常简单或者干脆是固定的字符串,那么可以使用nginx快速实现,这样就不用编写程序响应请求了,可以减少服务器资源占用并且响应性能非常快。

如何实现:

```
location /get_text {
    #这里也可以设置成text/plain
    default_type text/html;
    return 200 "This is nginx's text";
}
location /get_json{
    default_type application/json;
    return 200 '{"name":"TOM","age":18}';
}
```
  • 自定义服务日志

    Nginx中日志的类型分access.log、error.log。

    access.log:用来记录用户所有的访问请求。

    error.log:记录nginx本身运行时的错误信息,不会记录用户的访问请求。

    Nginx服务器支持对服务日志的格式、大小、输出等进行设置,需要使用到两个指令,分别是access_log和log_format指令。

    • access_log:

    用来设置用户访问日志的相关属性。

名称
语法 access_log path[format[buffer=size]]
默认值 access_log logs/access.log combined;
位置 http,server,location
  • log_format
用来指定日志的输出格式。
名称
语法 log_format name [escape=default
默认值 log_format combined “…”;
位置 http
  • 其他配置指令

    • sendfile

    用来设置Nginx服务器是否使用sendfile()传输文件,该属性可以大大提高Nginx处理静态资源的性能

名称
语法 sendfile on
位置 http、server、location
  • keepalive_timeout
用来设置长连接的超时时间。
名称
语法 keepalive_timeout time;
默认值 keepalive_timeout 75s;
位置 http、server、location

为什么要使用keepalive?我们都知道HTTP是一种无状态协议,客户端向服务端发送一个TCP请求,服务端响应完毕后断开连接。
如何客户端向服务端发送多个请求,每个请求都需要重新创建一次连接,效率相对来说比较多,使用keepalive模式,可以告诉服务器端在处理完一个请求后保持这个TCP连接的打开状态,若接收到来自这个客户端的其他请求,服务端就会利用这个未被关闭的连接,而不需要重新创建一个新连接,提升效率,但是这个连接也不能一直保持,这样的话,连接如果过多,也会是服务端的性能下降,这个时候就需要我们进行设置其的超时时间。

  • keepalive_requests
用来设置一个keep-alive连接使用的次数。
名称
语法 keepalive_requests number;
默认值 keepalive_requests 100;
位置 http、server、location

反向代理

正向代理

正向代理,意思是一个位于客户端和原始服务器(origin server)之间的服务器,为了从原始服务器取得内容,客户端向代理发送一个请求并指定目标(原始服务器),然后代理向原始服务器转交请求并将获得的内容返回给客户端。客户端才能使用正向代理。

image-20211024185246438

反向代理

反向代理服务器位于用户与目标服务器之间,但是对于用户而言,反向代理服务器就相当于目标服务器,即用户直接访问反向代理服务器就可以获得目标服务器的资源。同时,用户不需要知道目标服务器的地址,也无须在用户端作任何设定。反向代理服务器通常可用来作为Web加速,即使用反向代理作为Web服务器的前置机来降低网络和服务器的负载,提高访问效率

image-20211024185536432

负载均衡

负载均衡,英文名称为Load Balance,其含义就是指将负载(工作任务)进行平衡、分摊到多个操作单元上进行运行,例如FTP服务器、Web服务器、企业核心应用服务器和其它主要任务服务器等,从而协同完成工作任务。

负载均衡构建在原有网络结构之上,它提供了一种透明且廉价有效的方法扩展服务器和网络设备的带宽、加强网络数据处理能力、增加吞吐量、提高网络的可用性和灵活性。

image-20211024185756099

动静分离

动静分离是指在web服务器架构中,将静态页面与动态页面或者静态内容接口和动态内容接口分开不同系统访问的架构设计方法,进而提升整个服务访问性能和可维护性。

image-20211024185830752