Nginx deployment and configuration optimization

nginx installation

Installation dependencies

yum -y install gcc gcc-c++ make unzip pcre pcre-devel zlib zlib-devel libxml2 libxml2-devel readline readline-devel ncurses ncurses-devel perl-devel perl-ExtUtils-Embed openssl-devel bash-complation net-tools lrzsz upzip zip

Download package

wget http://nginx.org/download/nginx-1.16.1.tar.gz -o /usr/local

Unzip, compile and install

cd /usr/local
tar -xf nginx-1.16.1.tar.gz
cd nginx-1.16.1
./configure --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module --with-http_flv_module --with-http_gzip_static_module --with-stream
make
make install

Configuration optimization

Reference link: The https://www.cnblogs.com/xuxubaobao/p/10863464.html
optimized configuration points are: nginx running user, nginx running worker process number, nginx maximum number of open files, nginx event processing model, enabling efficient transmission mode, connection timeout time, fastcgi tuning, gzip tuning, Expires cache tuning, anti-theft chain, kernel parameter optimization, system connection number optimization, etc.

Nginx configuration optimization: nginx.conf

cd /usr/local/nginx/conf
cat nginx.conf
user  root;
#修改为root级别,最大权限
worker_processes  4;
#工作进程,设置为本机cpu核数的一半即可,cpu核数查看:cat /proc/cpuinfo|grep processor | wc -l
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
#pid        logs/nginx.pid;
worker_rlimit_nofile 65535;
#Nginx最多可以打开文件数,与ulimit -n的值保持一致即可,参考/etc/security/limits.conf的nofile配置
events {
    
    
#Nginx事件处理模型
    worker_connections  65535;
    accept_mutex on;
    multi_accept on;
    #默认是on,设置为on后,多个worker按串行方式来处理连接,也就是一个连接只有一个worker被唤醒,其他的处于休眠状态,设置为off后,多个worker按并行方式来处理连接,也就是一个连接会唤醒所有的worker,直到连接分配完毕,没有取得连接的继续休眠。当你的服务器连接数不多时,开启这个参数会让负载有一定的降低,但是当服务器的吞吐量很大时,为了效率,可以关闭这个参数。
    use epoll;
    #epoll事件模型,处理效率高
}

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;
    #开启高效文件传输模式,sendfile指令指定nginx是否调用sendfile函数来输出文件,对于普通应用设为on,如果用来进行下载等应用磁盘IO重负载应用,可设置为off,以平衡磁盘与网络I/O处理速度,降低系统的负载。注意:如果图片显示不正常把这个改成off。
    tcp_nopush on;
    #必须在sendfile开启模式才有效,防止网路阻塞,积极的减少网络报文段的数量(将响应头和正文的开始部分一起发送,而不一个接一个的发送。)
    
    #keepalive_timeout  0;
    keepalive_timeout  65;
    #客户端连接保持会话超时时间,超过这个时间,服务器断开这个链接
    tcp_nodelay on;
    #防止网络阻塞,不过要包涵在keepalived参数才有效
    client_header_buffer_size 4k;
    #客户端请求头部的缓冲区大小,这个可以根据你的系统分页大小来设置,一般一个请求头的大小不会超过 1k,不过由于一般系统分页都要大于1k,所以这里设置为分页大小。分页大小可以用命令getconf PAGESIZE查看。
    open_file_cache max=65535 inactive=20s; 
    #打开文件指定缓存,默认是没有启用的,max指定缓存数量,建议和打开文件数一致,inactive 是指经过多长时间文件没被请求后删除缓存
    open_file_cache_valid 30s;
    #多长时间检查一次缓存的有效信息
    open_file_cache_min_uses 1;
    #指令中的inactive 参数时间内文件的最少使用次数,如果超过这个数字,文件描述符一直是在缓存中打开的,如上例,如果有一个文件在inactive 时间内一次没被使用,它将被移除。
    client_header_timeout 15;
    #设置请求头的超时时间,我们也可以把这个设置低些,如果超过这个时间没有发送任何数据,nginx将返回request time out的错误。
    client_body_timeout 15;
    #设置请求体的超时时间,我们也可以把这个设置低些,超过这个时间没有发送任何数据,和上面一样的错误提示。
    reset_timedout_connection on;
    #告诉nginx关闭不响应的客户端连接,这将会释放那个客户端所占有的内存空间。
    send_timeout 15; 
    #响应客户端超时时间,这个超时时间仅限于两个活动之间的时间,如果超过这个时间,客户端没有任何活动,nginx关闭连接
    server_tokens off;
    #并不会让nginx执行的速度更快,但它可以关闭在错误页面中的nginx版本数字,这样对于安全性是有好处的。
    client_max_body_size 200m;
    #上传文件大小限制
    gzip on;
    #开启压缩功能
    gzip_min_length 2k;
    #设置允许压缩的页面最小字节数,页面字节数从header头的Content-Length中获取,默认值是0,不管页面多大都进行压缩,建议设置成大于1K,如果小与1K可能会越压越大。
    gzip_buffers    4 32k;
    #压缩缓冲区大小,表示申请4个单位为32K的内存作为压缩结果流缓存,默认值是申请与原始数据大小相同的内存空间来存储gzip压缩结果。
    gzip_comp_level 6;
    #压缩比例,用来指定GZIP压缩比,1压缩比最小,处理速度最快,9压缩比最大,传输速度快,但是处理慢,也比较消耗CPU资源。
    gzip_types text/css text/javascript application/json application/javascript application/x-javascript application/xml;
    #用来指定压缩的类型,‘text/html’类型总是会被压缩;gzip_types text/html (默认不对js/css文件进行压缩),无论是否指定text/html默认已经压缩 ;不能用通配符 text/*
    gzip_vary on;
    #varyheader支持,改选项可以让前端的缓存服务器缓存经过GZIP压缩的页面,例如用Squid缓存经过nginx压缩的数据。
    
    fastcgi_connect_timeout    600;
    #指定连接到后端FastCGI的超时时间。
    fastcgi_send_timeout 600;
    #向FastCGI传送请求的超时时间。
    fastcgi_read_timeout 600;
    #指定接收FastCGI应答的超时时间。
    fastcgi_buffer_size 64k;
    #指定读取FastCGI应答第一部分需要用多大的缓冲区,默认的缓冲区大小为fastcgi_buffers指令中的每块大小,可以将这个值设置更小。
    fastcgi_buffers 4 64k;
    #指定本地需要用多少和多大的缓冲区来缓冲FastCGI的应答请求,如果一个php脚本所产生的页面大小为256KB,那么会分配4个64KB的缓冲区来缓存,如果页面大小大于256KB,那么大于256KB的部分会缓存到fastcgi_temp_path指定的路径中,但是这并不是好方法,因为内存中的数据处理速度要快于磁盘。一般这个值应该为站点中php脚本所产生的页面大小的中间值,如果站点大部分脚本所产生的页面大小为256KB,那么可以把这个值设置为“8 32K”、“4 64k”等。
    fastcgi_busy_buffers_size 128k;
    #建议设置为fastcgi_buffers的两倍,繁忙时候的buffer
    fastcgi_temp_file_write_size 128k;
    #在写入fastcgi_temp_path时将用多大的数据块,默认值是fastcgi_buffers的两倍,该数值设置小时若负载上来时可能报502BadGateway
    fastcgi_temp_path /usr/local/nginx/nginx_tmp;
    #缓存临时目录
    fastcgi_intercept_errors on;
    #这个指令指定是否传递4xx和5xx错误信息到客户端,或者允许nginx使用error_page处理错误信息。
    fastcgi_cache_path /usr/local/nginx/fastcgi_cache levels=1:2 keys_zone=cache_fastcgi:128m inactive=1d max_size=10g;
    #fastcgi_cache缓存目录,可以设置目录层级,比如1:2会生成16*256个子目录,cache_fastcgi是这个缓存空间的名字,cache是用多少内存(这样热门的内容nginx直接放内存,提高访问速度),inactive表示默认失效时间,如果缓存数据在失效时间内没有被访问,将被删除,max_size表示最多用多少硬盘空间。
    fastcgi_cache cache_fastcgi;
    #表示开启FastCGI缓存并为其指定一个名称。开启缓存非常有用,可以有效降低CPU的负载,并且防止502的错误放生。cache_fastcgi为proxy_cache_path指令创建的缓存区名称
    fastcgi_cache_valid 200 302 1h;
    #用来指定应答代码的缓存时间,实例中的值表示将200和302应答缓存一小时,要和fastcgi_cache配合使用
    fastcgi_cache_valid 301 1d;
    #将301应答缓存一天
    fastcgi_cache_valid any 1m;
    #将其他应答缓存为1分钟
    fastcgi_cache_min_uses 1;
    #该指令用于设置经过多少次请求的相同URL将被缓存。
    fastcgi_cache_key http://$host$request_uri;
    #该指令用来设置web缓存的Key值,nginx根据Key值md5哈希存储.一般根据$host(域名)、$request_uri(请求的路径)等变量组合成proxy_cache_key 。
    #fastcgi_pass;
    #指定FastCGI服务器监听端口与地址,可以是本机或者其它
#总结:
#nginx的缓存功能有:proxy_cache / fastcgi_cache

#proxy_cache的作用是缓存后端服务器的内容,可能是任何内容,包括静态的和动态。
#fastcgi_cache的作用是缓存fastcgi生成的内容,很多情况是php生成的动态的内容。
#proxy_cache缓存减少了nginx与后端通信的次数,节省了传输时间和后端宽带。
#fastcgi_cache缓存减少了nginx与php的通信的次数,更减轻了php和数据库(mysql)的压力。
#CGI是为了保证web server传递过来的数据是标准格式的,方便CGI程序的编写者。Fastcgi是用来提高CGI程序性能的。php-fpm是fastcgi进程的管理器,用来管理fastcgi进程的

    server {
    
    
        listen       80;
        server_name  localhost;
        #charset koi8-r;
        #access_log  logs/host.access.log  main;
        location / {
    
    
            root   html;
            index  index.html index.htm;
        }
        #缓存,主要针对于图片,css,js等元素更改机会比较少的情况下使用,特别是图片,占用带宽大,我们完全可以设置图片在浏览器本地缓存365d,css,js,html可以缓存个10来天,这样用户第一次打开加载慢一点,第二次,就非常快了。缓存的时候,我们需要将需要缓存的拓展名列出来,expires缓存配置在server字段里面。
        #expire功能优点 
			#1、expires可以降低网站购买的带宽,节约成本
			#2、同时提升用户访问体验
			#3、减轻服务的压力,节约服务器成本,是web服务非常重要的功能。 
		#expire功能缺点
			#1、被缓存的页面或数据更新了,用户看到的可能还是旧的内容,反而影响用户体验
		#解决办法:
			#1、第一个缩短缓存时间,例如:1天,但不彻底,除非更新频率大于1天
			#2、第二个对缓存的对象改名。
        location ~* \.(ico|jpe?g|gif|png|bmp|swf|flv)$ {
    
    
                expires 30d;
  		#log_not_found off;
  		access_log off;
	}
        location ~* \.(js|css)$ {
    
    
		expires 7d;
	        log_not_found off;
		access_log off;
	} 
#注:log_not_found off;是否在error_log中记录不存在的错误。默认是。

#防止别人直接从你网站引用图片等链接,消耗了你的资源和网络流量,那么我们的解决办法由几种: 
#1、水印,品牌宣传,你的带宽,服务器足够 
#2、防火墙,直接控制,前提是你知道IP来源 
#3、防盗链策略下面的方法是直接给予404的错误提示

#参数可以使如下形式:
#none 意思是不存在的Referer头(表示空的,也就是直接访问,比如直接在浏览器打开一个图片)
#blocked 意为根据防火墙伪装Referer头,如:“Referer:XXXXXXX”。
#server_names 为一个或多个服务器的列表,0.5.33版本以后可以在名称中使用“*”通配符。

        location ~*^.+\.(jpg|gif|png|swf|flv|wma|wmv|asf|mp3|mmf|zip|rar)$ {
    
    
            valid_referers noneblocked  www.benet.com benet.com;
    	    if ($invalid_referer) {
    
    
     	    #return 302  http://www.benet.com/img/nolink.jpg;
      		return 404;
        	break;
    	    }
            access_log off;
        }  	
        #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;
    #    }
    #}
include      /usr/local/nginx/conf/conf.d/*.conf;
#include 优化,在conf下创建子目录的方式配置新的分支配置文件
}
cd /usr/local/nginx
cat conf/nginx.conf | egrep -v '^$|#'

Insert picture description here

Server kernel parameter optimization: /etc/sysctl.conf

cat > /etc/sysctl.conf <<EOF
fs.file-max = 655350
#系统打开的最大文件数
net.ipv4.ip_forward = 1
#开启转发
net.ipv4.ip_local_port_range= 1024 65535
#表示用于向外连接的端口范围。缺省情况下很小,改为1024到65535。
net.ipv4.tcp_keepalive_time= 1200
#表示当keepalive起用的时候,TCP发送keepalive消息的频度。缺省是2小时,改为20分钟。
net.ipv4.tcp_max_syn_backlog= 20480
#表示SYN队列的长度,默认为1024,加大队列长度为8192,可以容纳更多等待连接的网络连接数。
net.ipv4.tcp_max_tw_buckets= 5000
#表示系统同时保持TIME_WAIT的最大数量,如果超过这个数字,TIME_WAIT将立刻被清除并打印警告信息。默认为180000,改为5000。此项参数可以控制TIME_WAIT的最大数量,只要超出了。
net.ipv4.tcp_synack_retries= 2
#为了打开对端的连接,内核需要发送一个SYN并附带一个回应前面一个SYN的ACK。也就是所谓三次握手中的第二次握手。这个设置决定了内核放弃连接之前发送SYN+ACK包的数量。
net.ipv4.tcp_syn_retries= 2
#在内核放弃建立连接之前发送SYN包的数量。
net.ipv4.tcp_max_orphans= 3276800
#系统中最多有多少个TCP套接字不被关联到任何一个用户文件句柄上,如果超过这个数字,连接将即刻被复位并打印出警告信息,这个限制仅仅是为了防止简单的DoS攻击,不能过分依靠它或者人为地减小这个值,更应该增加这个值(如果增加了内存之后)。
net.ipv4.tcp_keepalive_probes = 3
net.ipv4.tcp_keepalive_intvl = 30
net.ipv4.tcp_syncookies= 1
#表示开启SYNCookies。当出现SYN等待队列溢出时,启用cookies来处理,可防范少量SYN攻击,默认为0,表示关闭;
net.ipv4.tcp_tw_reuse= 1
#表示开启重用。允许将TIME-WAITsockets重新用于新的TCP连接,默认为0,表示关闭;
net.ipv4.tcp_tw_recycle= 1
#表示开启TCP连接中TIME-WAITsockets的快速回收,默认为0,表示关闭;
net.ipv4.tcp_fin_timeout= 30
#修改系統默认的TIMEOUT 时间。
net.ipv4.tcp_mem = 786432 1048576 1572864
#同样有3个值,意思是:
#net.ipv4.tcp_mem[0]:低于此值,TCP没有内存压力。
#net.ipv4.tcp_mem[1]:在此值下,进入内存压力阶段。
#net.ipv4.tcp_mem[2]:高于此值,TCP拒绝分配socket。
#上述内存单位是页,而不是字节。可参考的优化值是:786432 1048576 1572864
net.ipv4.tcp_wmem = 8192 436600 873200
#TCP写buffer,可参考的优化值:8192 436600 873200
net.ipv4.tcp_rmem = 32768 436600 873200
#TCP读buffer,可参考的优化值:32768 436600 873200
net.ipv4.tcp_retries2 = 5

net.ipv4.conf.default.rp_filter = 1
net.ipv4.conf.default.accept_source_route = 0
net.ipv4.conf.lo.arp_ignore = 0
net.ipv4.conf.lo.arp_announce = 0
net.ipv4.conf.all.arp_ignore = 0

net.core.netdev_max_backlog= 32768
#每个网络接口接收数据包的速率比内核处理这些包的速率快时,允许送到队列的数据包的最大数目。
net.core.somaxconn= 32768
#例如web应用中listen函数的backlog默认会给我们内核参数的net.core.somaxconn限制到128,而nginx定义的NGX_LISTEN_BACKLOG默认为511,所以有必要调整这个值。
net.core.wmem_default= 8388608
net.core.rmem_default= 8388608
net.core.rmem_max= 16777216
#最大socket读buffer,可参考的优化值:873200
net.core.wmem_max= 16777216
#最大socket写buffer,可参考的优化值:873200

net.core.wmem_max = 873200
net.core.rmem_max = 873200
net.core.somaxconn = 10240
net.core.netdev_max_backlog = 20480

kernel.msgmnb = 65536
kernel.msgmax = 65536
kernel.shmmax = 68719476736
kernel.shmall = 4294967296
kernel.sysrq = 0
kernel.core_uses_pid = 1

vm.overcommit_memory = 1
vm.max_map_count = 655350
EOF
sysctl -p     #执行生效

Insert picture description here

Optimization of the number of system connections: /etc/security/limits.conf

cat > /etc/security/limits.conf <<EOF
#进程的最大数目优化
* soft nproc 20480
* hard nproc 20480
#打开文件的最大数目优化,root用户和其他用户
root soft nofile 655350
root hard nofile 655350
* soft nofile 655350
* hard nofile 655350
#用户级别的锁内存优化
isi soft memlock unlimited
isi hard memlock unlimited
EOF

Insert picture description here

Start nginx and set it to start automatically

Start nginx and visit the test

cd /usr/local/nginx
./sbin/nginx -t  			 #校验配置文件
./sbin/nginx      			 #启动nginx
netstat -tanlp |grep nginx   #查看nginx的监听端口
ps -ef |grep nginx           #查看nginx的启动进程

Insert picture description here

Set to enable self-start

cat  > /etc/init.d/nginxd <<EOF
#!/bin/bash
#chkconfig: 2345 35 80
#description: nginx
#processname: nginx

nginx_home="/usr/local/nginx"

case "$1" in
    start)
    ${nginx_home}/sbin/nginx
    echo "$(date) nginx is started"  >> ${nginx_home}/nginx-status.log
    ;;
    stop)
    ${nginx_home}/sbin/nginx -s stop
    echo "$(date) nginx is stopped" >> ${nginx_home}/nginx-status.log
    ;;
    reload)
    ${nginx_home}/sbin/nginx -s reload
    echo "$(date) nginx is restarted" >> ${nginx_home}/nginx-status.log
    ;;
    status)
	nginx_pid_num=$(ps -ef |grep nginx |egrep "master|work"|grep -v grep |wc -l)
	if [ $nginx_pid_num -ne 0 ];then
            echo "$(date) nginx is running"
        else 
            echo "$(date) nginx is stopped"
        fi
    ;;
    *)
    echo "Usage: $0 {start|stop|reload|status}"
    ;;
esac
EOF
chmod +x /etc/init.d/nginxd
chkconfig --add /etc/init.d/nginxd
chkconfig --list nginxd

Comes with a complete version of nginx configuration file

#################################### 用户级别、work数、事件优化 ####################################
user  root;
worker_processes  4;
worker_rlimit_nofile 65535;
events {
    
    
    worker_connections  65535;
    accept_mutex on;
    multi_accept on;
    use epoll;
}

http {
    
    
    include       mime.types;
    default_type  application/octet-stream;
#################### 高效传输模式、连接超时时间、fastcgi调优、gzip调优 #############################
    sendfile on;
    tcp_nopush on;
########################################## 高效传输模式 ############################################    
    keepalive_timeout  65;
    tcp_nodelay on;
    open_file_cache max=65535 inactive=20s; 
    open_file_cache_valid 30s;
    open_file_cache_min_uses 1;
    client_header_timeout 15;
    client_body_timeout 15;
    reset_timedout_connection on;
    send_timeout 15; 
    server_tokens off;
    client_max_body_size 200m;
########################################### gzip调优 ###############################################
    gzip on;
    gzip_min_length 2k;
    gzip_buffers    4 32k;
    gzip_comp_level 6;
    gzip_types text/css text/javascript application/json application/javascript application/x-javascript application/xml;
    gzip_vary on;
###################################### fastcgi调优,可以不配置 #######################################
    fastcgi_connect_timeout    600;
    fastcgi_send_timeout 600;
    fastcgi_read_timeout 600;
    fastcgi_buffer_size 64k;
    fastcgi_buffers 4 64k;
    fastcgi_busy_buffers_size 128k;
    fastcgi_temp_file_write_size 128k;
    fastcgi_temp_path /usr/local/nginx/nginx_tmp;
    fastcgi_intercept_errors on;
    fastcgi_cache_path /usr/local/nginx/fastcgi_cache levels=1:2 keys_zone=cache_fastcgi:128m inactive=1d max_size=10g;
    fastcgi_cache cache_fastcgi;
    fastcgi_cache_valid 200 302 1h;
    fastcgi_cache_valid 301 1d;
    fastcgi_cache_valid any 1m;
    fastcgi_cache_min_uses 1;
    fastcgi_cache_key http://$host$request_uri;

    server {
    
    
        listen       80;
        server_name  localhost;
        location / {
    
    
            root   html;
            index  index.html index.htm;
        }
################################## 可以不配置 ####################################
        location ~* \.(js|css)$ {
    
    
		    expires 7d;
	        log_not_found off;
		    access_log off;
	    } 
        location ~*^.+\.(jpg|gif|png|swf|flv|wma|wmv|asf|mp3|mmf|zip|rar)$ {
    
    
            valid_referers noneblocked  www.benet.com benet.com;
    	    if ($invalid_referer) {
    
    
      		return 404;
        	break;
    	    }
            access_log off;
        } 
################################################################################     	
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
    
    
            root   html;
        }
    }
include      /usr/local/nginx/conf/conf.d/*.conf;
}

Guess you like

Origin blog.csdn.net/weixin_44729138/article/details/109022489