1、环境介绍
操作系统:centos 7.9
cpu:8核心
内存:8g
nginx:http://nginx.org/en/download.html选怎stable版本
地址规划:
nginx01 10.99.50.118
nginx02 10.99.50.119
vip1 10.99.50.120
vip2 10.99.50.121

2、升级内核
导入public key

rpm --import https://www.elrepo.org/RPM-GPG-KEY-elrepo.org

安装epel源

yum install https://www.elrepo.org/elrepo-release-7.el7.elrepo.noarch.rpm

查看可用版本内核

yum --disablerepo="*" --enablerepo="elrepo-kernel" list available

nginx proxy_read_timeout proxy_send_timeout 区别 nginx proxy keepalive_nginx


选择安装ml最新版本

yum --enablerepo=elrepo-kernel install kernel-ml

查看系统上可以用的内核

awk -F\' '$1=="menuentry " {print i++ " : " $2}' /etc/grub2.cfg

nginx proxy_read_timeout proxy_send_timeout 区别 nginx proxy keepalive_配置文件_02


设置启动内核

grub2-set-default 0

重启验证

reboot
uname -r

nginx proxy_read_timeout proxy_send_timeout 区别 nginx proxy keepalive_运维_03


3、系统参数设置

关闭防火墙和selinux

nginx proxy_read_timeout proxy_send_timeout 区别 nginx proxy keepalive_运维_04


修改最大打开文件数

vi /etc/security/limits.conf

最后添加

* hard nofile 65535
* soft nofile 65535

重启或者重新登陆生效

nginx proxy_read_timeout proxy_send_timeout 区别 nginx proxy keepalive_配置文件_05

4、下载并解压nginx

wget http://nginx.org/download/nginx-1.20.2.tar.gz
tar -xvf nginx-1.20.2.tar.gz

5、上传nginx-sticky-module-ng模块到/root下

模块下载地址https://download.csdn.net/download/zyj81092211/83463219

nginx proxy_read_timeout proxy_send_timeout 区别 nginx proxy keepalive_nginx_06


6、安装编译工具

yum install -y gcc
yum install -y gcc-c++
yum install -y pcre pcre-devel
yum install -y zlib zlib-devel
yum install -y openssl openssl-devel
yum -y install GeoIP GeoIP-devel GeoIP-data

7、进入nginx软件目录开始编译

./configure --prefix=/usr/local/nginx --with-threads --with-http_ssl_module --with-http_v2_module --with-http_realip_module  --with-http_gunzip_module --with-http_gzip_static_module --with-http_stub_status_module --with-http_sub_module --with-stream --with-stream=dynamic --with-stream_ssl_module --with-stream_realip_module --with-stream_geoip_module --with-stream_geoip_module=dynamic --with-stream_ssl_preread_module --add-module=/root/nginx-sticky-module-ng
make
make install

8、创建nginx运行用户

useradd nginx -s /sbin/nologin -M

9、nginx主配置文件
注意:根据自己环境和需求修改配置文件

# 加载模块写在最顶端
# 加载stream流模块
load_module /usr/local/nginx/modules/ngx_stream_module.so;
# 普通用户启动 (useradd nginx -s /sbin/nologin -M)
user nginx;

# 配置nginx worker进程个数
worker_processes 8;
worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000 01000000 10000000;
#worker_cpu_affinity 0001 0010 0100 1000 0001 0010 1000 0001 0010 0100 1000;

#worker_processes 4;
#worker_cpu_affinity 0001 0010 0100 1000;

#worker_processes 2;
#worker_cpu_affinity 0101 1010;

# 配置日志存放路径
#access_log  logs/accesslog.log  warn;
error_log   logs/error.log error;
pid logs/nginx.pid;

# nginx事件处理模型优化
events {
    worker_connections 51200; # 当个进程允许的客户端最大连接数
    use epoll;
    }

# 配置nginx worker进程最大打开文件数
worker_rlimit_nofile 65535;

http {
    
    # 隐藏版本号
    server_tokens off;
    
    # 设置日志格式
    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/accesslog.log  main;        
    # 开启高效文件传输模式
    include mime.types;                         # 媒体类型
    default_type    application/octet-stream;   # 默认媒体类型
    charset  utf-8;                             # 默认字符集
    sendfile    on;
    tcp_nopush  on;                             # 只有在sendfile开启模式下有效
    
    # 设置连接超时时间
    keepalive_timeout  65;      # 设置客户端连接保持会话的超时时间,超过则服务器会关闭该连接
    tcp_nodelay on;             # 打开tcp_nodelay,在包含了keepalive参数才有效果
    client_header_timeout 15;    # 设置客户端请求有超时时间,该时间内客户端未发送数据,nginx将返回‘Request time out(408)’错误
    client_body_timeout 15;    # 设置客户端请求体超时时间,同上
    send_timeout 15;            # 设置相应客户端的超时时间,超时nginx将会关闭连接
    
    # 上传文件大小设置(动态引用)
    client_max_body_size 10m;
    
    # 数据包头部缓存大小
    client_header_buffer_size    1k;        #默认请求包头信息的缓存    
    large_client_header_buffers  4 4k;      #大请求包头部信息的缓存个数与容量
   
    # 压缩处理
    gzip on;                           #开启压缩
    gzip_min_length 1k;                #小文件不压缩
    gzip_comp_level 4;                 #压缩比率
    gzip_buffers 4 16k;                #压缩缓冲区大小,申请4个单位为16K的内存作为亚索结果流缓存    
    gzip_http_version 1.1;             # 默认压缩版本
    #对特定文件压缩,类型参考mime.types
    gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
    gzip_vary on;
    gzip_disable "MSIE[1-6]\."; 
    
    # 设置fastcgi
    fastcgi_cache_path /usr/local/nginx/fastcgi_cache levels=1:2
                keys_zone=TEST:10m
                inactive=5m;       # 为FastCGI缓存指定一个路径,目录结构等级,关键字区域存储时间和非活动删除时间
    fastcgi_cache_key "$scheme$request_method$host$request_uri";
    fastcgi_connect_timeout 300;   # 指定连接到后端FastCGI的超时时间
    fastcgi_send_timeout 300;      # 向FastCGI传送请求的超时时间,这个值是指已经完成两次握手后向FastCGI传送请求的超时时间   
    fastcgi_read_timeout 300;      # 接收FastCGI应答的超时时间,这个值是指已经完成两次握手后接收FastCGI应答的超时时间    
    fastcgi_buffer_size 16k;       # 缓冲区大小 
    fastcgi_buffers 16 16k;
    fastcgi_busy_buffers_size 16k;      
    fastcgi_temp_file_write_size 16k;   # 在写入fastcgi_temp_path时将用多大的数据块,默认值是fastcgi_buffers的两倍  
    fastcgi_cache TEST;                 # 开启FastCGI缓存并且为其制定一个名称
    fastcgi_cache_valid 200 302 1h;
    fastcgi_cache_valid 301 1d;
    fastcgi_cache_valid any 1m;         # 为指定的应答代码指定缓存时间,上例中将200,302应答缓存一小时,301应答缓存1天,其他为1分钟
    fastcgi_cache_min_uses 1;           # 5分钟内某文件1次也没有被使用,那么这个文件将被移除
    fastcgi_cache_use_stale error timeout invalid_header http_500;
    
    # 内存缓存
    open_file_cache   max=2000  inactive=20s; #设置服务器最大缓存文件数量,关闭20秒内无请求的文件
    open_file_cache_valid    60s;             #文件句柄的有效时间是60秒,60秒后过期     
    open_file_cache_min_uses 5;               #只有访问次数超过5次会被缓存  
    open_file_cache_errors   off;

   # 引入子配置文件     
    include vhost/*.conf;

}


#配置tcp代理,需要额外加载stream相关模块
stream {
#
#    upstream cloudsocket {
#       hash $remote_addr consistent;
#      # $binary_remote_addr;
#      server 192.168.182.155:3306 weight=5 max_fails=3 fail_timeout=30s;
#    }
#    server {
#       listen 3306;#数据库服务器监听端口
#       proxy_connect_timeout 10s;
#       proxy_timeout 300s;#设置客户端和代理服务之间的超时时间,如果5分钟内没操作将自动断开。
#       proxy_pass cloudsocket;
#    }
   # 引入子配置文件     
    include stream/*.conf;
}

测试配置文件

/usr/local/nginx/sbin/nginx -t

nginx proxy_read_timeout proxy_send_timeout 区别 nginx proxy keepalive_nginx_07


启动nginx

/usr/local/nginx/sbin/nginx

10、创建http子配置文件和示例
创建子配置文件夹

mkdir /usr/local/nginx/conf/vhost

httptes.com.conf示例

upstream backend{
#保持会话连接,开启调度算法ip_hash,url_hash(加载三方模块),sticky(cookie方式,加载nginx-sticky-module-ng模块)
sticky;
server 10.99.50.126:30842 weight=1 max_fails=2 fail_timeout=10;
server 10.99.50.127:30842 weight=1 max_fails=2 fail_timeout=10;
server 10.99.50.128:30842 weight=1 max_fails=2 fail_timeout=10;
server 10.99.50.129:30842 weight=1 max_fails=2 fail_timeout=10;
server 10.99.50.130:30842 weight=1 max_fails=2 fail_timeout=10;
server 10.99.50.131:30842 weight=1 max_fails=2 fail_timeout=10;
server 10.99.50.132:30842 weight=1 max_fails=2 fail_timeout=10;
#server 192.168.2.101 down;#标记为down 剔除负载均衡队列
}


server
{
    listen 80;
    #include agent_deny.conf; #加载防止爬虫的配置文件
    server_name httptest.com;
    #access_log logs/test.com.access.log main;
    #error_log logs/test.comerror.log  error;
    proxy_buffering on; #开启buffer缓存,异步应答客户端请求,效率高
    proxy_buffer_size 4k;
    proxy_buffers 2 4k;
    proxy_busy_buffers_size 4k;
    proxy_temp_path /tmp/nginx_proxy_tmp 1 2;
    proxy_max_temp_file_size 20M;
    proxy_temp_file_write_size 8k;
    
    location /
    {
        proxy_pass      http://backend;
        proxy_set_header Host   $host;
        proxy_set_header X-Real-IP      $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

server {
    listen 443 ssl;
    server_name  httptest.com;
    #access_log logs/test.com.access.log main;
    #error_log logs/test.comerror.log  error;
    ssl_certificate     /usr/local/nginx/cert/test.pem;
    #ssl_certificate     /usr/local/nginx/cert/test.crt;
    ssl_certificate_key /usr/local/nginx/cert/test.key;
    ssl_session_timeout 5m;
    ssl_protocols  TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers   ALL:!DH:!EXPORT:!RC4:+HIGH:+MEDIUM:-LOW:!aNULL:!eNULL;
    ssl_prefer_server_ciphers  on;
    add_header Access-Control-Allow-Origin *;
    add_header Access-Control-Allow-Headers X-Requested-Wit,content-typeh;
    add_header Access-Control-Allow-Methods GET,POST,OPTIONS;
    location /
    {
        proxy_pass      http://backend;
        proxy_set_header Host   $host;
        proxy_set_header X-Real-IP      $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

创建证书目录(把证书按配置文件重命名放到此文件夹)

mkdir /usr/local/nginx/cert

上面配置文件可以打开注释,加载爬虫配置文件
示例:

#禁止Scrapy等工具的抓取
if ($http_user_agent ~* (Scrapy|Curl|HttpClient)) {
     return 403;
}
 
#禁止指定UA及UA为空的访问
if ($http_user_agent ~ "WinHttp|WebZIP|FetchURL|node-superagent|java/|
FeedDemon|Jullo|JikeSpider|Indy Library|Alexa Toolbar|AskTbFXTV|AhrefsBot|
CrawlDaddy|Java|Feedly|Apache-HttpAsyncClient|UniversalFeedParser|ApacheBench|
Microsoft URL Control|Swiftbot|ZmEu|oBot|jaunty|Python-urllib|
lightDeckReports Bot|YYSpider|DigExt|HttpClient|MJ12bot|heritrix|EasouSpider|Ezooms|BOT/0.1|
YandexBot|FlightDeckReports|Linguee Bot|^$" ) {
     return 403;             
}

12、创建TCP子配置文件和示例
创建子配置文件夹

mkdir /usr/local/nginx/conf/stream

配置文件例子tcp.conf

upstream stream_server{
                 server 10.99.50.222:3389;#被代理的服务器
}
server {
                 listen 8888;#代理服务器端口
                 proxy_connect_timeout 8s;#连接超时
                 proxy_timeout 24h;#代理服务器超时
                 proxy_pass stream_server;#明确指定被代理服务器
}

13、安装keepalive

yum install keepalived -y

14、keepalive配置文件
nginx01:

! Configuration File for keepalived

global_defs {     #global全局配置段
   
#notification_email {
#        root@localhost     #设置邮件的接受人地址
#}
#   notification_email_from  kaadmin@hehe.com   #发送邮件的人,此处可以自行定义;
#   smtp_server 127.0.0.1    #配置邮件服务器地址,默认为本地即可;
#   smtp_connect_timeout 30   #连接邮件服务器的超时时间;
#   router_id LVS_DEVEL   
}

vrrp_script chk_nginx {    #检测nginx是否在线脚本;如果nginx服务不在线,则当前节点权重减10;
        script "/etc/keepalived/nginx_check.sh"
        interval 1
        weight -10

}

vrrp_instance VI_1 {   #第一个虚拟路由器实例1配置
    state MASTER    #初始状态为主角色;
    interface ens192   #虚拟地址所在的网卡接口名称;
    virtual_router_id 200  #虚拟路由器实例的id号,同一个虚拟路由器实例两端id号必须相同;
    priority 100   #优先级,数字越大,优先级越高;
    advert_int 1  #健康状态监测时长间隔;
    authentication {   #认证相关配置
        auth_type PASS  #字符认证
        auth_pass 1111  #认证密码
    }
    virtual_ipaddress {  
        10.99.50.120 #配置虚拟ip地址;   
    }
    track_script {
        chk_nginx    #此处调用上面的nginx状态检查脚本
    }
}
vrrp_instance VI_2 {   #虚拟路由器实例二的配置段
    state BACKUP    #因为是互相为主备,所以第二个虚拟路由器实例的初始状态为备节点;
    interface ens192   #虚拟地址所在的网卡接口名称;
    virtual_router_id 210 #虚拟路由器实例的id号,同一个虚拟路由器实例两端id号必须相同;
    priority 99    #优先级设定;
    advert_int 1  #状态检查时长间隔;
    authentication {   #认证类型
        auth_type PASS
        auth_pass 2222
    }
    virtual_ipaddress {    
        10.99.50.121  #虚拟路由器实例二的ip地址;
    }
    track_script {
        chk_nginx  #同样调用nginx健康状态检查脚本;
    }
}

nginx02:

! Configuration File for keepalived

global_defs {     #global全局配置段
   
#notification_email {
#        root@localhost     #设置邮件的接受人地址
#}
#   notification_email_from  kaadmin@hehe.com   #发送邮件的人,此处可以自行定义;
#   smtp_server 127.0.0.1    #配置邮件服务器地址,默认为本地即可;
#   smtp_connect_timeout 30   #连接邮件服务器的超时时间;
#   router_id LVS_DEVEL   
}

vrrp_script chk_nginx {    #检测nginx是否在线脚本;如果nginx服务不在线,则当前节点权重减10;
        script "/etc/keepalived/nginx_check.sh"
        interval 1
        weight -10

}

vrrp_instance VI_1 {   #第一个虚拟路由器实例1配置
    state BACKUP    #初始状态为备用角色;
    interface ens192   #虚拟地址所在的网卡接口名称;
    virtual_router_id 200  #虚拟路由器实例的id号,同一个虚拟路由器实例两端id号必须相同;
    priority 99   #优先级,数字越大,优先级越高;
    advert_int 1  #健康状态监测时长间隔;
    authentication {   #认证相关配置
        auth_type PASS  #字符认证
        auth_pass 1111  #认证密码
    }
    virtual_ipaddress {  
        10.99.50.120  #配置虚拟ip地址;   
    }
    track_script {
        chk_nginx    #此处调用上面的nginx状态检查脚本
    }
}
vrrp_instance VI_2 {   #虚拟路由器实例二的配置段
    state MASTER    #因为是互相为主备,所以第二个虚拟路由器实例的初始状态为备节点;
    interface ens192   #虚拟地址所在的网卡接口名称;
    virtual_router_id 210 #虚拟路由器实例的id号,同一个虚拟路由器实例两端id号必须相同;
    priority 100    #优先级设定;
    advert_int 1  #状态检查时长间隔;
    authentication {   #认证类型
        auth_type PASS
        auth_pass 2222
    }
    virtual_ipaddress {    
        10.99.50.121  #虚拟路由器实例二的ip地址;
    }
    track_script {
        chk_nginx  #同样调用nginx健康状态检查脚本;
    }
}

15、ngixn检查脚本

#!/bin/bash
counter=$(ps -C nginx --no-heading|wc -l)
if [ "${counter}" = "0" ]; then
    /usr/local/nginx/sbin/nginx
    sleep 2
    counter=$(ps -C nginx --no-heading|wc -l)
    if [ "${counter}" = "0" ]; then
        /etc/init.d/keepalived stop
    fi
fi

16、启动keepalive

systemctl start keepalived
systemctl enable keepalived

nginx proxy_read_timeout proxy_send_timeout 区别 nginx proxy keepalive_配置文件_08

nginx proxy_read_timeout proxy_send_timeout 区别 nginx proxy keepalive_缓存_09

补充
设置nginx systemd启动

vi /usr/lib/systemd/system/nginx.service

添加如下

[Unit]
Description=nginx
After=network.target

[Service]
Type=forking
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s quit
PrivateTmp=true

[Install]
WantedBy=multi-user.target

启动nginx

systemctl start nginx
 systemctl enable nginx