Appearance
连接优化
优化连接配置可以提高Nginx性能。
基本配置
Keep-Alive
nginx
keepalive_timeout 65;
keepalive_requests 100;TCP优化
nginx
tcp_nopush on;
tcp_nodelay on;完整配置
生产环境配置
nginx
http {
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
keepalive_requests 100;
keepalive_disable msie6;
}参数说明
keepalive_timeout
65
- Keep-Alive超时时间(秒)
- 默认值:65
- 推荐值:60-120
keepalive_requests
100
- 单个连接的最大请求数
- 默认值:100
- 推荐值:100-1000
tcp_nopush
on
- 启用tcp_nopush
- 减少网络包数量
- 提高传输效率
tcp_nodelay
on
- 启用tcp_nodelay
- 减少延迟
- 提高响应速度
完整示例
生产环境配置
nginx
http {
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
keepalive_requests 100;
keepalive_disable msie6;
# 客户端连接
client_body_timeout 12;
client_header_timeout 12;
send_timeout 10;
# 缓冲区
client_body_buffer_size 128k;
client_max_body_size 10m;
client_header_buffer_size 1k;
large_client_header_buffers 4 4k;
}客户端连接优化
超时设置
nginx
client_body_timeout 12;
client_header_timeout 12;
send_timeout 10;说明:
- client_body_timeout:读取请求体超时
- client_header_timeout:读取请求头超时
- send_timeout:发送响应超时
缓冲区设置
nginx
client_body_buffer_size 128k;
client_max_body_size 10m;
client_header_buffer_size 1k;
large_client_header_buffers 4 4k;说明:
- client_body_buffer_size:请求体缓冲区大小
- client_max_body_size:最大请求体大小
- client_header_buffer_size:请求头缓冲区大小
- large_client_header_buffers:大请求头缓冲区
完整示例
生产环境配置
nginx
http {
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
keepalive_requests 100;
keepalive_disable msie6;
# 客户端连接
client_body_timeout 12;
client_header_timeout 12;
send_timeout 10;
# 缓冲区
client_body_buffer_size 128k;
client_max_body_size 10m;
client_header_buffer_size 1k;
large_client_header_buffers 4 4k;
# Gzip压缩
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;
}性能测试
查看连接数
bash
netstat -an | grep :80 | wc -l查看连接状态
bash
netstat -an | grep :80 | awk '{print $6}' | sort | uniq -c压力测试
bash
ab -n 10000 -c 100 http://example.com/常见问题
连接超时
原因: keepalive_timeout设置过小
解决: 增加keepalive_timeout
nginx
keepalive_timeout 120;请求体过大
原因: client_max_body_size设置过小
解决: 增加client_max_body_size
nginx
client_max_body_size 20m;总结
连接优化的关键点:
- keepalive_timeout:设置合理的超时时间
- keepalive_requests:设置合理的请求数
- tcp_nopush:启用tcp_nopush
- tcp_nodelay:启用tcp_nodelay
- 客户端连接:设置超时和缓冲区
合理优化连接配置,提高Nginx性能。