目录:
1.安装nginx
2.配置nginx
3.调优nginx
4.性能测试
ps:为了方便,文档使用docker容器来操作的。
1.安装nginx
1.1 启动容器、download nginx 以及编译前的修改
启动容器
liwangdeMacBook-Air:~ liwang$ docker run -i -t --name nginx_server_01 -v /Users/liwang/docker/nginx_data:/data -p : centos /bin/bash
将文件copy至容器中
liwangdeMacBook-Air:~ liwang$ docker ..tar.gz
解压
[root@e46ae471064e soft]# .tar.gz -C /soft/
安装之前修改源码屏蔽名称以及版本号
[root@e46ae471064e core]# ls -l "/soft/nginx-1.14.0/src/core/nginx.h" -rw-r--r-- Apr : /soft/nginx-/src/core/nginx.h [root@e46ae471064e core]# ------------------------------------------------------ #define NGINX_VERSION "0.0.1" #define NGINX_VER "HaiYan/" NGINX_VERSION #define NGINX_VAR "HaiYan" ------------------------------------------------------ #define NGINX_VERSION "1.14.0" #define NGINX_VER "nginx/" NGINX_VERSION #define NGINX_VAR "NGINX" ------------------------------------------------------
1.2 安装nginx
安装插件
[root@e46ae471064e ~]# yum install pcre pcre-devel gcc gcc-c++ make openssl openssl-devel -y
添加用户
[root@e46ae471064e nginx-]# useradd nginx -s /sbin/nologin -M
安装
[root@e46ae471064e nginx-]# ./configure --prefix=/usr/local/nginx --with-http_ssl_module --with-http_stub_status_module --user=nginx --group=nginx [root@e46ae471064e nginx-]# make [root@e46ae471064e nginx-]# make install
启动nginx,利用curl工具获取服务器信息
[root@e46ae471064e conf]# /usr/local/nginx/sbin/nginx [root@e46ae471064e nginx]# curl -I localhost HTTP/ OK Server: HaiYan/ Date: Tue, May :: GMT Content-Type: text/html Content-Length: Last-Modified: Tue, May :: GMT Connection: keep-alive ETag: "5ae87ab6-264" Accept-Ranges: bytes [root@e46ae471064e nginx]#
详细可安装信息可用./configure --help获取
2.配置nginx
1、nginx虚拟主机配置
基于域名的虚拟主机
[root@e46ae471064e conf]# cat nginx.conf | grep -v "#" | grep -v "^$" >> extra/www.conf 修改www.conf效果如下: [root@e46ae471064e extra]# cat www.conf server { listen ; server_name www.wang-li.top; location / { root html/www; index index.html index.htm; } error_page /50x.html; location = /50x.html { root html; } } [root@e46ae471064e extra]#
修改nginx.conf 在http区间增加,include extra/*; 这行
[root@e46ae471064e conf]# cat nginx.conf | grep -v "#" | grep -v "^$" worker_processes ; events { worker_connections ; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout ; server { listen ; server_name localhost; location / { root html; index index.html index.htm; } error_page /50x.html; location = /50x.html { root html; } } include extra/*; } [root@e46ae471064e conf]#
增加html/www/index.html文件
[root@e46ae471064e conf]# ls /usr/local/nginx/html/www/index.html -l -rw-r--r-- root root May : /usr/local/nginx/html/www/index.html [root@e46ae471064e conf]#
修改hosts文件,访问信息如下
[root@e46ae471064e conf]# cat /etc/hosts | grep www.wang-li.top 127.0.0.1 www.wang-li.top [root@e46ae471064e conf]# curl -I www.wang-li.top HTTP/ OK Server: HaiYan/ Date: Tue, May :: GMT Content-Type: text/html Content-Length: Last-Modified: Tue, May :: GMT Connection: keep-alive ETag: "5ae87ead-265" Accept-Ranges: bytes [root@e46ae471064e conf]#
基于端口的虚拟主机
修改www.conf基于端口的访问,如下:
[root@e46ae471064e extra]# cat www.conf server { listen ; server_name www.wang-li.top; location / { root html/www; index index.html index.htm; } error_page /50x.html; location = /50x.html { root html; } } [root@e46ae471064e extra]#
reload nginx 访问如下
[root@e46ae471064e extra]# /usr/local/nginx/sbin/nginx -t nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful [root@e46ae471064e extra]# /usr/local/nginx/sbin/nginx -s reload [root@e46ae471064e extra]# curl -I www.wang-li.top: HTTP/ OK Server: HaiYan/ Date: Tue, May :: GMT Content-Type: text/html Content-Length: Last-Modified: Tue, May :: GMT Connection: keep-alive ETag: "5ae87ead-265" Accept-Ranges: bytes [root@e46ae471064e extra]#
基于IP的虚拟主机
获取容器ip
liwangdeMacBook-Air:~ liwang$ docker inspect -f {{.NetworkSettings.IPAddress}} nginx_server_01 172.17.0.2 liwangdeMacBook-Air:~ liwang$
修改www.conf如下
[root@e46ae471064e extra]# cat www.conf server { listen ; server_name www.wang-li.top; location / { root html/www; index index.html index.htm; } error_page /50x.html; location = /50x.html { root html; } } [root@e46ae471064e extra]#
reload后访问如下:
[root@e46ae471064e extra]# curl -I HTTP/ OK Server: HaiYan/ Date: Tue, May :: GMT Content-Type: text/html Content-Length: Last-Modified: Tue, May :: GMT Connection: keep-alive ETag: "5ae87ead-265" Accept-Ranges: bytes [root@e46ae471064e extra]#
2、nginx stub_status配置
查看系统是否支持此模块
[root@e46ae471064e extra]# /usr/local/nginx/sbin/nginx -V nginx version: HaiYan/ built by (Red Hat -) (GCC) built with OpenSSL Jan TLS SNI support enabled configure arguments: --prefix=/usr/local/nginx --with-http_ssl_module --with-http_stub_status_module --user=nginx --group=nginx [root@e46ae471064e extra]#
发现有--with-http_stub_status_module就是支持的
配置www.conf如下:
[root@e46ae471064e extra]# cat www.conf server { listen ; server_name www.wang-li.top; location / { # root html/www; # index index.html index.htm; stub_status on; access_log off; } } [root@e46ae471064e extra]#
reload后访问如下
root@e46ae471064e extra]# curl www.wang-li.top Active connections: server accepts handled requests Reading: Writing: Waiting: [root@e46ae471064e extra]#
三个值分别代表:
active connections:正在处理的连接活动数
21 21 20
第一个表示从启动到现在一共处理了21次请求
第二个表示建立了21次握手
第三个表示总共处理了20次请求
丢包数 = 握手数-连接数 可见,并未丢包
reading: nginx 读取到客户端的header信息数
writing: Nginx 返回给客户端的header信息数
waiting: Nginx 处理完等待下一次请求指令的驻留连接,在开启keep-alive的情况下,这个值等于active - (reading + writing)
3、nginx_location:
作用:根据不同的URI来执行不同的应用
语法:
location [ = | ~ | ~* | ^- ] url {
...
}
语法规则: location [=|~|~*|^~] /uri/ { … }
= 开头表示精确匹配
^~ 开头表示uri以某个常规字符串开头,理解为匹配 url路径即可。nginx不对url做编码,因此请求为/static/20%/aa,可以被规则^~ /static/ /aa匹配到(注意是空格)。
~ 开头表示区分大小写的正则匹配
~* 开头表示不区分大小写的正则匹配
!~和!~*分别为区分大小写不匹配及不区分大小写不匹配 的正则
/ 通用匹配,任何请求都会匹配到。
~和~*的区别: ~区分大小写, ~* 不区分大小写
= :为精确配置
/ :为默认配置
案例:
利用location来实现根据URI来访问不同的内容,实现功能:访问www.wang-li.top/bbs/XXX时,能够抓取和www.wang-li.top不同的位置
配置如下
[root@e46ae471064e conf]# sed -n "47,59p" nginx.conf location ^~ /bbs/ { root html/bbs; index index.html; # } location / { root html; index index.html index.htm; # } [root@e46ae471064e conf]# tree /usr/local/nginx/html/ /usr/local/nginx/html/ |-- 50x.html |-- bbs | `-- bbs | `-- index.html |-- index.html `-- www `-- index.html directories, files [root@e46ae471064e conf]#
访问如下:
[root@e46ae471064e conf]# curl localhost <!DOCTYPE html> <html> <head> <title>Welcome to nginx!</title> <style> body { width: 35em; margin: auto; font-family: Tahoma, Verdana, Arial, sans-serif; } </style> </head> <body> <h1>Welcome to nginx!</h1> <p>If you see this page, the nginx web server is successfully installed and working. Further configuration is required.</p> <p>For online documentation and support please refer to <a href="http://nginx.org/">nginx.org</a>.<br/> Commercial support is available at <a href="http://nginx.com/">nginx.com</a>.</p> <p><em>Thank you for using nginx.</em></p> </body> </html> [root@e46ae471064e conf]# curl localhost/bbs/ Welcome www.wang-li.top PPS [root@e46ae471064e conf]#
4、nginx alias 和 root的区别
基于上诉的nginx location,location 和 alias的差别就在于
root会带入上诉的url路径去判断,而alias则不会,举例:
location ^~ /bbs/ {
root html/bbs;
index index.html;
#
}
这段说明:当我的url中包含bbs时,会去执行location的内容,而内容包含root html/bbs,现在如果输入localhost\bbs\时,系统会去检查本地文件html/bbs/bbs/...这下面的内容
而alias则不会
修改如下:
[root@e46ae471064e bbs]# sed -n "48,58p" /usr/local/nginx/conf/nginx.conf location ^~ /bbs/ { alias html/bbs/; index index.html; # } location / { root html; index index.html index.htm; # } [root@e46ae471064e bbs]# cat /usr/local/nginx/html/bbs/index.html alias liwag bbs site [root@e46ae471064e bbs]# [root@e46ae471064e bbs]# curl localhost/bbs/ alias liwag bbs site [root@e46ae471064e bbs]#
5、nginx rewrite:
语法:
rewrite ^/(.*) url/$1 permanent;
意思是只要匹配如下^/(.*),就跳转至url上,且$1是取前面regex部分括号的内容,结尾的primanent是永久301重定向标记。
regex语法:
\:去掉特殊字符
^:起始位置
$:结束位置
*:匹配0次或多次
+:匹配前面的字符一次或多次
?:匹配前面的字符0次或1次
.:匹配\n之外的任何字符
(pattern):匹配括号内字符,并可以在后面匹配,常用$0-$9属性获取值
rewrite flag标记
last:本条规则匹配完成后,继续向下匹配
break:本条规则匹配完成后,不再匹配后面的规则
redirect:返回302临时重定向,
permanent:返回301永久重定向
例子,为实现需求,访问 网址/blog 时跳转至www.cnblogs.com:
[root@e46ae471064e conf]# sed -n "33,39p" nginx.conf #gzip on; server { listen ; server_name localhost; rewrite ^/(.*)/blog http://www.cnblogs.com/$1 permanent; [root@e46ae471064e conf]# curl -I localhost/wang-li/blog HTTP/ Moved Permanently Server: HaiYan/ Date: Fri, May :: GMT Content-Type: text/html Content-Length: Connection: keep-alive Location: http://www.cnblogs.com/wang-li [root@e46ae471064e conf]#
3.nginx调优
1.修改默认用户,有两种方式其一是修改nginx.conf中的内容,但是事先用户必须在系统中存在,其二为编译时就指定用户和用户组
其一:
[root@e46ae471064e conf]# grep "nginx" /etc/passwd nginx:x::::/home/nginx:/sbin/nologin [root@e46ae471064e conf]# sed -n "3,6p" nginx.conf user nginx nginx; worker_processes ; #error_log logs/error.log; [root@e46ae471064e conf]#
其二:
[root@e46ae471064e conf]# /usr/local/nginx/sbin/nginx -V nginx version: HaiYan/ built by (Red Hat -) (GCC) built with OpenSSL Jan TLS SNI support enabled configure arguments: --prefix=/usr/local/nginx --with-http_ssl_module --with-http_stub_status_module --user=nginx --group=nginx [root@e46ae471064e conf]#
在编译时指定user和group
2.设置nginx worker cpu核数和cpu affinity
设置nginx worker cpu核数一般设置为系统CPU核数或者是其倍数
查看系统cpu核数
[root@e46ae471064e conf]# cat /proc/cpuinfo | grep processor | wc -l [root@e46ae471064e conf]#
修改后nginx worker为:
[root@e46ae471064e conf]# sed -n "3,6p" nginx.conf worker_processes ; #error_log logs/error.log; #error_log logs/error.log notice; [root@e46ae471064e conf]#
cpu affinity([əˈfɪnɪti])的目的是为了设置cpu分布,让其均匀分布在各个cpu上
配置如下:
[root@e46ae471064e conf]# sed -n "3,5p" nginx.conf worker_processes ; worker_cpu_affinity ; [root@e46ae471064e conf]#
配置之后top命令如下:
[root@e46ae471064e conf]# top -n top - :: up :, users, load average: 0.00, 0.00, 0.00 Tasks: total, running, sleeping, stopped, zombie %Cpu(s): 3.2 us, 0.0 sy, 0.0 ni, 96.8 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st KiB Mem : total, used, buff/cache KiB Swap: total, used. avail Mem PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND root S :00.56 bash root S :00.01 nginx nginx S :00.00 nginx nginx S :00.00 nginx nginx S :00.00 nginx nginx S :00.00 nginx root R :00.00 top
3.调整nginx 工作模式为epoll,来处理高并发事件
[root@e46ae471064e conf]# sed -n "12,17p" nginx.conf events { use epoll; worker_connections ; } [root@e46ae471064e conf]#
4.设置nginx worker进程最大打开文件描述符数目,最好还是与系统ulimit保持一致
[root@e46ae471064e conf]# ulimit -n [root@e46ae471064e conf]#
配置conf如下:
[root@e46ae471064e conf]# sed -n "3,6p" nginx.conf worker_processes ; worker_cpu_affinity ; worker_rlimit_nofile ; [root@e46ae471064e conf]#
5.配置nginx最多的连接数
配置如下:
[root@e46ae471064e conf]# sed -n "10,20p" nginx.conf #pid logs/nginx.pid; events { use epoll; worker_connections ; } http { [root@e46ae471064e conf]#
6.优化超时连接时间
当超过设定时间还未连接成功的话,则会断开
[root@e46ae471064e conf]# sed -n "30,35p" nginx.conf sendfile on; #tcp_nopush on; #keepalive_timeout ; keepalive_timeout ; [root@e46ae471064e conf]#
7.优化客户端请求头超时时间以及请求body超时时间
此设置主要是为了防止客户端利用http进行攻击,如果在设置时间内没有发送完整的header或则body,则会返回request time out错误
[root@e46ae471064e conf]# sed -n "34,39p" nginx.conf keepalive_timeout ; client_header_timeout ; client_body_timeout ; #gzip on; [root@e46ae471064e conf]#
8.优化客户端超时时间
如果超过设置时间,客户端还未有任何动作,nginx则会断掉此连接
[root@e46ae471064e conf]# sed -n "34,39p" nginx.conf keepalive_timeout ; client_header_timeout ; client_body_timeout ; send_timeout ; [root@e46ae471064e conf]#
附上nginx.conf如下(仅供参考)
[root@e46ae471064e conf]# cat nginx.conf | grep -v "^$" | grep -v "#" worker_processes ; worker_cpu_affinity ; worker_rlimit_nofile ; events { use epoll; worker_connections ; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout ; client_header_timeout ; client_body_timeout ; send_timeout ; server { listen ; server_name localhost; rewrite ^/(.*)/blog http://www.cnblogs.com/$1 permanent; location ^~ /bbs/ { alias html/bbs/; index index.html; } location / { root html; index index.html index.htm; } }} [root@e46ae471064e conf]#
4.性能测试
利用ab压力测试工具进行测试结果如下:
[root@e46ae471064e conf]# ab -c -n localhost/ 参数说明,-c 为并发数 -n 为总请求数 总请求数需要大于并发数 This is ApacheBench, Version $> Copyright Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ Licensed to The Apache Software Foundation, http://www.apache.org/ 上述介绍ab工具版本等等信息 Benchmarking localhost (be patient) Completed requests Completed requests Completed requests Completed requests Completed requests Completed requests Completed requests Completed requests Completed requests Completed requests Finished requests Server Software: HaiYan/ Server Hostname: localhost Server Port: show 出服务器信息以及访问信息端口等 Document Path: / Document Length: bytes 请求路劲以及文件大小 Concurrency Level: Time taken for tests: 1.024 seconds 整个测试持续的时间 Complete requests: 完成的请求数量 Failed requests: 失败数 Write errors: Total transferred: bytes HTML transferred: bytes Requests per second: 9769.13 [#/sec] (mean) 平均返回数据时间 Time per request: 1.024 [ms] (mean) 平均响应时间 Time per request: 0.102 [ms] (mean, across all concurrent requests) 平均并发响应时间 Transfer rate: 500944.38 [Kbytes/sec] received Connection Times (ms) min mean[+/-sd] median max Connect: Processing: Waiting: Total: 响应时间的值 Percentage of the requests served within a certain time (ms) % % % % % % % % % (longest request) 请求的平均速度 [root@e46ae471064e conf]#
2.测试未调优之前的nginx
[root@e46ae471064e conf]# ab -c -n localhost/ This is ApacheBench, Version $> Copyright Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ Licensed to The Apache Software Foundation, http://www.apache.org/ Benchmarking localhost (be patient) Completed requests Completed requests Completed requests Completed requests Completed requests Completed requests Completed requests Completed requests Completed requests Completed requests Finished requests Server Software: HaiYan/ Server Hostname: localhost Server Port: Document Path: / Document Length: bytes Concurrency Level: Time taken for tests: 3.910 seconds Complete requests: Failed requests: (Connect: , Receive: , Length: , Exceptions: ) Write errors: Total transferred: bytes HTML transferred: bytes Requests per second: 7672.50 [#/sec] (mean) Time per request: 260.671 [ms] (mean) Time per request: 0.130 [ms] (mean, across all concurrent requests) Transfer rate: 379256.45 [Kbytes/sec] received Connection Times (ms) min mean[+/-sd] median max Connect: Processing: Waiting: Total: Percentage of the requests served within a certain time (ms) % % % % % % % % % (longest request) [root@e46ae471064e conf]#
3.测试调优之后的nginx
[root@e46ae471064e conf]# ab -c -n localhost/ This is ApacheBench, Version $> Copyright Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ Licensed to The Apache Software Foundation, http://www.apache.org/ Benchmarking localhost (be patient) Completed requests Completed requests Completed requests Completed requests Completed requests Completed requests Completed requests Completed requests Completed requests Completed requests Finished requests Server Software: HaiYan/ Server Hostname: localhost Server Port: Document Path: / Document Length: bytes Concurrency Level: Time taken for tests: 5.894 seconds Complete requests: Failed requests: Write errors: Total transferred: bytes HTML transferred: bytes Requests per second: 5090.28 [#/sec] (mean) Time per request: 392.906 [ms] (mean) Time per request: 0.196 [ms] (mean, across all concurrent requests) Transfer rate: 261020.94 [Kbytes/sec] received Connection Times (ms) min mean[+/-sd] median max Connect: Processing: Waiting: Total: Percentage of the requests served within a certain time (ms) % % % % % % % % % (longest request) [root@e46ae471064e conf]#
通过上述比对,即可发现调优之前和调优之后的差距,可以清晰的看到未调优前测试失败的请求数量29911,而调优后失败的请求数量为0。