Debian 上优化 Node.js 运行环境的可执行清单
一 基础运行时与版本管理
nvm install 18 && nvm use 18 && nvm alias default 18;NodeSource 安装示例(以 18.x 为例)为 curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash - && sudo apt-get install -y nodejs。完成后用 node -v、npm -v 校验。二 进程管理与多核利用
pm2 start app.js -i max 按 CPU 核数 启动工作进程,显著提升吞吐与容错。fork 多个工作进程共享同一端口,提高响应速度与稳定性。三 网络与系统层面优化
ulimit -n 65535;永久在 /etc/security/limits.conf 增加 * soft nofile 65535 与 * hard nofile 65535。net.core.somaxconn = 65535、net.ipv4.tcp_max_syn_backlog = 65535、net.ipv4.ip_local_port_range = 1024 65535、net.ipv4.tcp_tw_reuse = 1、net.ipv4.tcp_fin_timeout = 30,执行 sudo sysctl -p 生效。四 内存与 V8 引擎调优
export NODE_OPTIONS="--max_old_space_size=4096" 将堆上限设为 4GB,请结合实例内存与业务实测调整)。五 监控 分析与资源隔离
sudo cgcreate -g memory,cpu:/nodejs;sudo cgset -r memory.limit_in_bytes 268435456 /nodejs(限制为 256MB);sudo cgset -r cpu.shares 512 /nodejs;将进程加入 cgroup:sudo cgclassify -g memory,cpu:/nodejs <PID>;监控:sudo cgget -g memory,cpu:/nodejs。