版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_22075041/article/details/83622008
监控
nginx有自带的监控模块,编译nginx的时候,加上参数 --with-http_stub_status_module
#配置指令
./configure --prefix=/usr/local
--user=nginx
--group=nginx
--with-http_ssl_module
--with-http_realip_module
--http-client-body-temp-path=/usr/local/var/tmp/nginx/client
--http-proxy-temp-path=/usr/local/var/tmp/nginx/proxy
--http-fastcgi-temp-path=/usr/local/var/tmp/nginx/fcgi
--http-scgi-temp-path=/usr/local/var/tmp/nginx/scgi
--http-uwsgi-temp-path=/usr/local/var/tmp/nginx/uwsgi
--with-http_geoip_module
--with-http_stub_status_module
然后修改nginx配置文件,添加监控状态配置
location = /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
那么访问nginx的状态,就可以通过 curl 127.0.0.1/nginx_status访问了
很简单的一个模块,除了这个还有外部的工具比如:ngxtop监控请求信息
ngxtop 安装:
安装python-pip
yum install epel-release
yum install python-pip
安装ngxtop
pip install ngxtop
常用指令如下:
ngxtop
ngxtop top remote_addr 查看访问最多的IP
ngxtop -i 'status >= 400' print request status http_referer 列出4xx or 5xx 的相应
指定配置文件:ngxtop -c /etc/nginx/nginx.conf
查询状态是200:ngxtop -c /etc/nginx/nginx.conf -i 'status==200'
查询访问最多ip:ngxtop -c /etc/nginx/nginx.conf -g remote_addr
还有一种图像化工具nginx-rrd,但是需要和php整合,感兴趣的自行研究啊
我常干的nginx优化
1.配置线程数和并发数
worker_processes 4 #cpu(取决于cpu的核数(如,2个四核的cpu计为8),也可以配置成auto,让nginx自己选择工作线程数)
events{
worker_connections 10240;#每一个进程打开的最大连接数,包含了nginx与客户端和nginx与upstream之间的连接(受限于操作系统)
multi_accept on; #可以一次建立多个连接
use epoll; # Linux下多路复用IO接口select/poll的增强版本,它能显著提高程序在大量并发连接中只有少量活跃的情况下的系统CPU利用率
}
2.配置后端Server的长连接
upstream server_pool{
server localhost:8080 weight=1 max_fails=2 fail_timeout=30s;
server localhost:8081 weight=1 max_fails=2 fail_timeout=30s;
keepalive 300;#300个长连接
}
location /{
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_pass http://server_pool/;
}
3.启用缓存、压缩。nginx的缓存我认为还有很大的局限性,下面是我的静态文件压缩配置
gzip on;
gzip_disable "msie6";
gzip_proxied any;
gzip_min_length 1000;
gzip_comp_level 6;
gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript;
4.操作系统优化
1》配置文件/etc/sysctl.conf,如下:
sysctl -w net.ipv4.tcp_syncookies=1 #防止一个套接字在有过多试图连接到达时引起过载
sysctl -w net.core.somaxconn=1024 #默认128,连接队列
sysctl -w net.ipv4.tcp_fin_timeout=10 #timewait的超时时间
sysctl -w net.ipv4.tcp_tw_reuse=1 #os直接使用timevait的连接
sysctl -w net.ipv4.tcp_tw_recycle=0 #回收禁用
2》配置文件/etc/security/limits.conf,如下:
hard nofile 204800
soft nofile 204800
soft core unlimited
soft stack 204800
5.其他优化
sendfile on; #减少文件在应用和内核之间的拷贝
tcp_nopush on; #当数据包达到一定大小再发送
tcp_nodelay off; #有数据随时发送(只用在应答需要非常快速的情况下)
测试nginx语法是否正确:nginx -t