Appearance
性能问题排查
本节介绍Nginx性能问题的排查方法。
响应慢
排查方法
查看响应时间
bash
curl -w "@curl-format.txt" -o /dev/null -s http://example.comcurl-format.txt内容:
time_namelookup: %{time_namelookup}\n
time_connect: %{time_connect}\n
time_appconnect: %{time_appconnect}\n
time_pretransfer: %{time_pretransfer}\n
time_redirect: %{time_redirect}\n
time_starttransfer: %{time_starttransfer}\n
----------\n
time_total: %{time_total}\n查看Nginx状态
nginx
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}查看状态
bash
curl http://localhost/nginx_status解决方法
启用缓存
nginx
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=proxy_cache:10m max_size=1g inactive=60m;
location / {
proxy_cache proxy_cache;
proxy_cache_valid 200 60m;
proxy_pass http://backend;
}启用Gzip
nginx
gzip on;
gzip_vary on;
gzip_min_length 1000;
gzip_comp_level 6;
gzip_types text/plain text/css text/xml text/javascript application/json application/javascript application/xml+rss;优化worker进程
nginx
worker_processes auto;
worker_connections 4096;CPU占用高
排查方法
查看CPU占用
bash
top -p $(pgrep nginx)查看Nginx进程
bash
ps aux | grep nginx查看CPU使用率
bash
mpstat -P ALL 1解决方法
减少worker进程
nginx
worker_processes 2;降低Gzip压缩级别
nginx
gzip_comp_level 4;禁用不必要的模块
nginx
# 禁用SSL模块(如果不需要)
# --without-http_ssl_module内存占用高
排查方法
查看内存占用
bash
free -h查看Nginx进程
bash
ps aux | grep nginx查看内存使用
bash
pmap $(pgrep nginx)解决方法
减少缓冲区大小
nginx
client_body_buffer_size 128k;
proxy_buffers 8 4k;减少worker进程
nginx
worker_processes 2;启用缓存清理
bash
# 配置日志轮转
sudo vi /etc/logrotate.d/nginx连接数过多
排查方法
查看连接数
bash
netstat -an | grep :80 | wc -l查看连接状态
bash
netstat -an | grep :80 | awk '{print $6}' | sort | uniq -c查看Nginx状态
bash
curl http://localhost/nginx_status解决方法
增加worker连接数
nginx
worker_connections 4096;启用限流
nginx
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
location / {
limit_req zone=one burst=5 nodelay;
}优化Keep-Alive
nginx
keepalive_timeout 65;
keepalive_requests 100;磁盘IO高
排查方法
查看磁盘IO
bash
iostat -x 1查看磁盘使用
bash
df -h查看磁盘IO
bash
iotop解决方法
启用缓存
nginx
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=proxy_cache:10m max_size=1g inactive=60m;优化日志
bash
# 配置日志轮转
sudo vi /etc/logrotate.d/nginx
# 或使用条件日志
map $request_uri $loggable {
~* \.(jpg|jpeg|png|gif|css|js)$ 0;
default 1;
}
access_log /var/log/nginx/access.log main if=$loggable;使用SSD
nginx
proxy_cache_path /ssd/cache/nginx levels=1:2 keys_zone=proxy_cache:10m max_size=1g inactive=60m;常见问题
性能优化后效果不明显
原因: 瓶颈在后端服务器
解决: 优化后端服务器或增加后端服务器
nginx
upstream backend {
server 192.168.1.10:8080;
server 192.168.1.11:8080;
server 192.168.1.12:8080;
}缓存命中率低
原因: 缓存配置不当
解决: 优化缓存配置
nginx
proxy_cache_key "$scheme$request_method$host$request_uri";
proxy_cache_valid 200 60m;总结
性能问题排查的关键点:
- 响应慢:启用缓存和Gzip,优化worker进程
- CPU占用高:减少worker进程,降低Gzip压缩级别
- 内存占用高:减少缓冲区大小,减少worker进程
- 连接数过多:增加worker连接数,启用限流
- 磁盘IO高:启用缓存,优化日志,使用SSD
掌握性能问题排查方法,优化Nginx性能。