一、核心优化方向
-
worker 进程配置
worker_processes auto;:自动匹配 CPU 核心数worker_connections 10240;:单进程最大连接数(需配合系统 ulimit)worker_rlimit_nofile 65535;:提升最大文件句柄数
-
事件模型优化
nginx
events { use epoll; multi_accept on; accept_mutex off; } -
TCP / 网络优化
nginx
http { sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; keepalive_requests 1000; } -
压缩优化
nginx
gzip on; gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; gzip_min_length 1k; -
静态资源缓存
nginx
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ { expires 30d; add_header Cache-Control "public, max-age=2592000"; } -
隐藏版本、提升安全
nginx
server_tokens off;
二、系统层面优化(配合 Nginx)
-
修改
/etc/security/limits.confplaintext
nginx soft nofile 65535 nginx hard nofile 65535 -
内核参数
/etc/sysctl.confplaintext
net.core.somaxconn = 65535 net.core.netdev_max_backlog = 65535 net.ipv4.tcp_syncookies = 1 net.ipv4.tcp_tw_reuse = 1 net.ipv4.tcp_fin_timeout = 30执行:
sysctl -p
三、监控指标与工具
1. 关键监控指标
- 活跃连接数、等待连接数
- 请求 QPS、响应时间
- 状态码:2xx/3xx/4xx/5xx 占比
- CPU、内存、句柄、磁盘 I/O
- upstream 后端健康状态
2. 内置状态页
nginx
location /nginx_status {
stub_status;
allow 127.0.0.1;
deny all;
}
访问:http://ip/nginx_status
3. 常用监控工具
nginx -t:配置语法检查nginx -s reload:平滑重载netstat -anp | grep nginx/ss -stop、htop、iostat、dstat- 日志分析:
awk、goaccess - 接入 Prometheus + Grafana(nginx-vts-exporter)
四、日志与排错
- 访问日志:记录请求、状态、耗时、UA、来源
- 错误日志:定位 upstream、权限、配置、端口冲突
- 常用排查:
- 502:后端服务挂 / 超时 / 不可达
- 504:超时
- 403:权限 / 目录索引 / IP 限制
- 404:路径 / 路由 / 文件不存在