系统内核参数调优
NGINX 性能不仅取决于自身配置,还受操作系统内核参数影响。调整网络栈和内存参数可进一步提升吞吐能力。
网络栈优化
TCP 连接参数
Bash
# /etc/sysctl.conf
# 增加连接队列
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65535
# TIME-WAIT 优化
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 15
# TCP keepalive
net.ipv4.tcp_keepalive_time = 600
net.ipv4.tcp_keepalive_intvl = 30
net.ipv4.tcp_keepalive_probes = 10
somaxconn控制 listen() 队列上限。tcp_tw_reuse允许复用 TIME-WAIT 连接(仅客户端安全)。
文件描述符
系统级限制
Bash
# /etc/sysctl.conf
fs.file-max = 1000000
# /etc/security/limits.conf
nginx soft nofile 65535
nginx hard nofile 65535
root soft nofile 65535
root hard nofile 65535
fs.file-max— 系统最大文件描述符数nofile— 单进程最大打开文件数
NGINX 的
worker_rlimit_nofile不应超过系统的nofile限制。高流量站点建议 65535+。
内存管理
虚拟内存和缓冲
Bash
# /etc/sysctl.conf
# 减少 swap 倾向
vm.swappiness = 10
# 增加本地端口范围
net.ipv4.ip_local_port_range = 1024 65535
# TCP 缓冲区自动调优
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.ipv4.tcp_rmem = 4096 87380 16777216
net.ipv4.tcp_wmem = 4096 65536 16777216
tcp_rmem/wmem三个值分别为:最小、默认、最大缓冲区大小(字节)。自动调优根据连接数动态调整。
网络优化
禁用不必要功能
Bash
# /etc/sysctl.conf
# 禁用 IPv6(如不使用)
net.ipv6.conf.all.disable_ipv6 = 1
# 禁用 IP 转发(非路由器)
net.ipv4.ip_forward = 0
# 启用 TCP SYN cookies(防 SYN flood)
net.ipv4.tcp_syncookies = 1
# 快速回收 TIME-WAIT
net.ipv4.tcp_max_tw_buckets = 262144
应用参数
立即生效
Bash
# 应用所有 sysctl 配置
sysctl -p
# 单独修改(立即生效,重启不保留)
sysctl -w net.core.somaxconn=65535
验证配置
Bash
# 查看当前值
sysctl net.core.somaxconn
sysctl net.ipv4.tcp_tw_reuse
# 查看 NGINX worker 文件描述符使用
cat /proc/$(cat /var/run/nginx.pid)/limits | grep "open files"
容器环境
Docker/Kubernetes 注意事项
YAML
# docker-compose.yml
services:
nginx:
image: nginx:latest
sysctls:
- net.core.somaxconn=65535
- net.ipv4.tcp_tw_reuse=1
ulimits:
nofile:
soft: 65535
hard: 65535
容器默认继承宿主机限制。需在容器配置中显式提升。Kubernetes 使用
securityContext和initContainers修改。
要点总结
net.core.somaxconn和tcp_max_syn_backlog提高连接队列上限tcp_tw_reuse = 1允许复用 TIME-WAIT 连接fs.file-max和nofile提高文件描述符上限- TCP 缓冲区自动调优根据连接动态调整
tcp_syncookies = 1防御 SYN flood 攻击- 修改
/etc/sysctl.conf确保重启后生效 - 容器环境需在运行时配置中显式设置
📝 发现内容有误?点击此处直接编辑