在 Ubuntu 上 Node.js 运行慢,可能由系统环境、Node 版本、代码问题或资源限制引起。下面按常见原因给你一套排查和优化思路。
可用工具:
top
htop
df -h
free -m
Ubuntu 自带 Node 可能很老(如 v10/v12)
查看版本:
node -v
建议安装 LTS 新版本(如 18 / 20 / 22):
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs
或用 nvm(推荐):
nvm install --lts
nvm use --lts
npm config set registry https://registry.npmmirror.com
pm2 常驻进程npm i -g pm2
pm2 start app.js
Node 高并发时容易受限:
ulimit -n
若很小(如 1024),可修改:
sudo nano /etc/security/limits.conf
添加:
* soft nofile 65535
* hard nofile 65535
❌ 错误:
const data = fs.readFileSync('big.json');
✅ 正确:
const data = await fs.promises.readFile('big.json');
const cluster = require('cluster');
const os = require('os');
if (cluster.isMaster) {
os.cpus().forEach(() => cluster.fork());
} else {
require('./app');
}
iostat -x 1
node --prof app.js
node --inspect app.js
或用:
clinic.js0xpm2 monit如果你愿意,可以告诉我:
我可以直接帮你定位具体原因。