• 从一个初学者的角度窥探Nginx


    标准Nginx配置模板

    
    #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;
    
    events {
        worker_connections  1024;
    }
    
    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;
    
        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;
        #    }
        #}
    }
    

    Nginx配置文件详解

    完整的Nginx配置文件是由六大部分组成:

    • main:全局设置
    • events:项工作模式设置
    • http:http设置
    • upstream:负载均衡设置
    • server:主机设置
    • location:URL设置
    main
    events {
        ...
    }
    http {
        ...
        upstream project_name {
        	...
    	}
    	server {
            ...
            location {
            	...
        	}
    		include /path/of/nginx/conf.d/*.conf;
        }
    }
    

    main 模块

    全局设置填写 Nginx 的全局配置,在此区域填写的内容会员应用到 Nginx 的全局。

    常用的全局配置:

    • worker_processes :Nginx 开启的子进程数
    • error_log :定义全局错误日志文件,可选值有:debug、info、notice、warn、error、crit
    • pid :指定进程 id 的存储文件位置
    • worker_rlimit_nofile :指定 Nginx 进程最多可以打开的文件描述符数目

    示例如下:

    # 定义 Nginx 运行的用户和用户组
    user nobody root;
    
    # Nginx 进程数(建议为 CPU 总核数,或者设置为 auto)
    worker_precesses 8;
    
    # 定义全局错误日志类型
    error_log /var/log/nginx/error.log info;
    
    #进程文件
    pid	/var/run/nginx.pid;
    
    # 一个 Nginx 进程最多可以打开的文件描述数目(建议与 ulimit -n 的值保持一致)
    worker_rlimit_nofile 65535;
    

    注:一般而言,此处的全局配置都可以保留默认设置(即什么都不用写)。

    events 模块

    用来指定 Nginx 的工作模式和单个进程的连接数上限。示例如下:

    events {
        # 参考事件模型,可选值有:kqueue、rtsing、epoll、/dev/poll、select、poll
        # epoll 模型是 Linux 2.6 以上版本内核中高性能网络 I/O 模型
        # FreeBSD 或者 macOS ,可使用 kqueue 模型
        use	epoll;
        
        #单个进程最大连接数(默认是 1024 ,最大连接数 = 连接数 x 进程数)
        worker_connections	65535;
    }
    

    注:上述进程的最大连接数受 Linux 系统进程的最大打开文件数的限制,只有在执行操作系统命令 [# ulimit -n 65536]后 worker_connections 的设置才能生效。

    http 模块

    http 部分是配置文件的最核心部分,它包括了绝大部分 HTTP 服务器相关属性的配置:

    • 是否适用 Keepalive
    • 是否适用 gzip 进行压缩
    • server 子模块
    • upstream 子模块

    示例如下:

    http {
        # 文件扩展名和文件类型映射表
        include	mime.types;
        
        # 默认文件类型
        default_type application/octet-stream;
        
        # 默认编码
        charset	utf-8;
        
        # 服务器名字的 hash 表大小
        server_name_hash_bucket_size 128;
        
        # 缓冲区代理缓冲用户端请求的最大字节数
        client_body_buffer_size 128k;
        
        # 允许客户端请求的最大单文件字节数
        client_max_body_size 10m;
        
        # 开启高效文件传输模式,启用之后 Nginx 会调用 sendfile 函数来输出文件
        # I/O 负载较大的应用,建议设置为 off,以平衡磁盘与网络 I/O 处理速度,减少系统负载
        sendfile on;
        
        # 开启目录列表访问(默认关闭)
        autoindex on;
        
        # 防止网络阻塞
        tcp_nopush on;
        tcp_nodelay on;
        
        # 长连接超时时间,单位为秒
        keepalive_timeout 120;
        
        # gzip 模块设置
        # 开启 gizp 压缩输出
        gzip on
        # 最小压缩文件的大小
        gizp_min_length 1k;
        # 压缩缓冲区
        gzip_buffers 4 16k;
        # 压缩版本
        gzip_http_version 1.1;
        # 压缩等级
        gzip_comp_level 2;
        # 压缩类型,默认类型已经包含 text/html,所以下面就用再写了
        gzip_types text/plain application/x-javacript text/css application/xml;
        # 会在响应头加个 Vary:Accept-Encodeing,可以让前端的缓存服务器缓存经过 gzip 压缩的页面
        gizp_vary on;
        # 在开启限制 IP 连接数的时候需要使用
        limit_zone crawler $binary_remote_addr 10m;
        
        upstream project_name {
            ...
        }
        server {
            ...
        }
    }
    

    server 模块

    server 模块是 http 的子模块,它可以定义一个虚拟主机,server {} 表示虚拟主机的配置范围。示例如下:

    server {
        # 用于指定虚拟主机的服务端口
        listen 8081;
        
        # 用于指定 IP 地址或者域名,多个域名直接用 空格分开
        server_name localhost www.nginx.com;
        
        # 表示在 server 这个虚拟主机内 Web 服务的跟目录
        root /nginx/www/path/;
        
        # 定义默认的首页地址
        index index.html index.htm;
        
        # 设置网页的默认编码格式
        charset utf-8;
        
        # 指定虚拟主机访问日志的存放路径,后面接上日志的输出格式
        access_log usr/local/var/log/host.access.log main;
        access_log usr/local/var/log/host.error.log error;
        
        location {
            ...
        }
    }
    

    location 模块

    location 模块是 Nginx 中可自定义程度最高的模块,location 如同它的名字一样是用来定位解析 URL 的,通过正则匹配,用户可以通过 location 指令实现对网页的各种处理。示例如下:

    location / {
        root /nginx/www/path;
        index index.html index.htm;
    }
    

    具体可查看:Nginx简单配置与使用

    upstream模块

    upstream模块又称为负载均衡模块。示例如下:

    upstream example.com {
        fair;
        server 172.17.1.1:80;
        server 172.17.1.2:8080 down;
        server 172.17.1.3:9999 max_fails=3 fail_timeout=20s max_conns=1000;
        server 172.17.1.4:2333 backup;
    }
    

    example.com 表示通过 upstream 指令定义了一个负载均衡的名称 。(名称可以任意指定,不一定是一个域名)

    fair是一种负载均衡调度算法。

    down 表示该 server 不参与负载均衡。

    backup 表示预留的备份机器,只有当其他所有非 backup 机器出现故障或异常忙碌是,才会请求 backup 机器,所以这台机器的负载压力很小。

    max_fails 表示允许请求失败的次数(默认为1次),当超过最大次数时返回 proxy_next_upstream 模块定义的错误。

    fail_timeout 表示在经历 max_fails 次失败后暂停服务的时间。

    max_conns 表示限制分配个后端服务器处理的最大连接数量,超过这个数量,将不会分配新的连接给它。

    官网配置说明文档: https://nginx.org/en/docs/http/ngx_http_core_module.html

    Nginx 负载均衡

    目前 Nginx 负载均衡模块共有4中调度算法。

    权重轮询

    weight轮询 每一个请求按照请求的时间顺序逐一分配到不同的后端服务器,如果后端某台服务器宕机,Nginx 轮询列表将自动去除该服务器,使用户访问不受影响。

    weight 用于指定轮询权值,weight 值越大,分配到访问的概率越高,主要用于后端服务器性能不均的情况。

    weight 轮询是 Nginx 的默认调度算法

    示例配置如下:

    upstream upstream.example.com {
        server 172.17.1.1:80 weight=1;
        server 172.17.1.2:8080 weight=1;
        server 172.17.1.3:9999 weight=10;
        server 172.17.1.4:2333 backup;
    }
    
    server {
        listen 80;
        server_name example.com;
        access_log /usr/local/var/log/nginx/access.log main;
        access_log /usr/local/var/log/nginx/error.log error;
        location / {
         	proxy_pass http://upstream.exaple.com;
            proxy_set_header X-Real-IP $remote_addr;
        }
    }
    

    此负载均衡配置的作用:(重启 Nginx:nginx -s reload)每次刷新页面,页面的请求会分别发送到前三台服务器,第四台是备份服务器,其中 第三台处理的请求最多,因为它的权重最大。

    IP 哈希

    ip_hash 根据 hash 算法对每一个请求中的访问 IP 进行处理。使来自同一个 IP 的访客固定访问一个后端服务器。

    这种方式可以简单而有效的解决动态网页存在的会话(session)共享问题。

    示例配置如下:

    upstream upstream.example.com {
        ip_hash;
        server 172.17.1.1:80;
        server 172.17.1.2:8080;
        server 172.17.1.3:9999;
        server 172.17.1.4:2333;
    }
    
    • 当负载均衡调度算法为 ip_hash 时,后端服务器的状态不能有 weight。因为这将导致流量分配不均匀。
    • 当负载均衡调度算法为 ip_hash 时,后端服务器的状态不能有 backup。因为访问已经固定,备份已经没有意义,同时会报错。

    Fair 调度

    fair 比前面两种更智能。这个算法可以根据页面的大小和加载时间的长短智能地进行负载均衡。

    简单来说,就是根据后端服务器的响应时间来分配请求,响应时间短的优先分配。

    Nginx 默认是不支持 fair 的,用户需要手动编译安装 Nginx 的 upstream_fair模块。下载地址: https://github.com/gnosek/nginx-upstream-fair

    [root@VM_0_6_centos local]# wget https://github.com/gnosek/nginx-upstream-fair/archive/master.zip
    [root@VM_0_6_centos local]# unzip master.zip
    

    进入到 Nginx 的安装目录下,下载 fair 模块源码,解压后的目录名为:nginx-upstream-fair-master

    重新编译 Nginx,将 fair 模块添加到编译参数。进入到 Nginx 源码目录下

    URL 哈希

    url_hash 根据 hash 算法对每个请求中的访问 url 进行处理,使来自同一个 url 的请求固定定向到同一个后端服务器,这样可以提高后端缓存服务器的效率。

    示例配置如下:

    upstream upstream.example.com {
        hash $request_uri;
        server 172.17.1.1:80;
        server 172.17.1.2:8080;
        server 172.17.1.3:9999;
        server 172.17.1.4:2333;
    }
    

    ==未完待续==

  • 相关阅读:
    Mybatis中的动态SQL
    Mybatis核心知识点
    Java8之Stream详解
    多线程知识点总结(二)
    多线程知识点总结(一)
    数据库中的行锁和表锁
    数据库中的sql完整性约束
    数据库中的sql语句总结
    全局变量
    打印 输出 debug
  • 原文地址:https://www.cnblogs.com/sayook/p/13048803.html
Copyright © 2020-2023  润新知