全部学科
NodeJS全栈
nodejs
Python全栈
python
小程序首页
📅 2026-05-20 7 分钟 ✍️ juanwangdev

系统内核参数调优

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 使用 securityContextinitContainers 修改。

要点总结

  • net.core.somaxconntcp_max_syn_backlog 提高连接队列上限
  • tcp_tw_reuse = 1 允许复用 TIME-WAIT 连接
  • fs.file-maxnofile 提高文件描述符上限
  • TCP 缓冲区自动调优根据连接动态调整
  • tcp_syncookies = 1 防御 SYN flood 攻击
  • 修改 /etc/sysctl.conf 确保重启后生效
  • 容器环境需在运行时配置中显式设置

📝 发现内容有误?点击此处直接编辑

← 上一篇 日志优化与缓冲
下一篇 → 缓存配置优化
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库