配置原则:工作进程数 = CPU 核心数 或 CPU 核心数 × 2
查看 CPU 核数:
# 方法1:top 命令后按 1
# 方法2:直接统计
grep ^processor /proc/cpuinfo | wc -l
配置示例:
# 编辑配置文件
vi /usr/local/nginx1.10/conf/nginx.conf
worker_processes 4; # 填写 CPU 核数或核数×2
# 重启生效
/usr/local/nginx1.10/sbin/nginx -s reload
# 验证进程
ps -aux | grep nginx | grep -v grep
验证结果:
root 9834 0.0 0.0 47556 1948 ? Ss 22:36 0:00 nginx: master process nginx
www 10135 0.0 0.0 50088 2004 ? S 22:58 0:00 nginx: worker process
www 10136 0.0 0.0 50088 2004 ? S 22:58 0:00 nginx: worker process
www 10137 0.0 0.0 50088 2004 ? S 22:58 0:00 nginx: worker process
www 10138 0.0 0.0 50088 2004 ? S 22:58 0:00 nginx: worker process
核心作用:绑定工作进程到指定 CPU 核心,减少进程切换开销。cpu的亲和能够使nginx对于不同的work工作进程绑定到不同的cpu上面去。就能够减少在work间不断切换cpu,把进程通常不会在处理器之间频繁迁移,进程迁移的频率小,来减少性能损耗。
限制说明:worker_processes 最大为 8,超过无性能提升且降低稳定性
配置示例:
# 4核 CPU 配置
worker_processes 4;
worker_cpu_affinity 0001 0010 0100 1000;
# 8核 CPU 配置
worker_processes 8;
worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000 01000000 10000000;
Nginx 层面配置:
worker_rlimit_nofile 65535; # 与系统最大打开文件数保持一致
系统层面配置(/etc/security/limits.conf):
* soft nofile 65535 # 软限制(警告阈值)
* hard nofile 65535 # 硬限制(绝对上限)
# linux 一切皆文件,网络连接socket也是