以下是在Linux上高效部署Node.js的方法:
環境準備
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
source ~/.bashrc
nvm install --lts
apt,CentOS用yum),適合快速部署基礎環境。部署應用
scp或git),安裝依賴:cd /path/to/project
npm install --production # 僅安裝生產依賴
npm install pm2 -g
pm2 start app.js --name "your-app" --watch # --watch 監聽文件變化自動重啟
性能優化
ulimit -n 65535(需在/etc/security/limits.conf中永久設置)。net.ipv4.tcp_tw_reuse = 1(在/etc/sysctl.conf中配置)。cluster模塊或PM2的集群模式,充分利用多核CPU。反向代理與負載均衡
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://localhost:3000;
proxy_set_header Host $host;
}
}
監控與日志
pm2 monit查看進程狀態和資源占用。安全與維護
npm outdated + npm update。sudo chown -R app_user:app_group /path/to/app。通過以上步驟,可實現Node.js在Linux上的高效、穩定部署,兼顧性能、可維護性和安全性。