在 Debian 系统上启动 Node.js 项目,常见做法取决于你是直接运行还是作为服务运行。下面按常见场景说明。
# 使用 apt 安装(版本可能较旧)
sudo apt update
sudo apt install nodejs npm -y
# 查看版本
node -v
npm -v
如需最新版,推荐使用 NodeSource 或 nvm
进入项目目录:
cd /path/to/your/project
运行入口文件(常见为 app.js 或 index.js):
node app.js
如果有 package.json:
npm install
npm start
&node app.js &
nohupnohup node app.js > app.log 2>&1 &
查看日志:
tail -f app.log
sudo nano /etc/systemd/system/nodeapp.service
示例内容:
[Unit]
Description=Node.js App
After=network.target
[Service]
Type=simple
User=your_user
WorkingDirectory=/path/to/your/project
ExecStart=/usr/bin/node /path/to/your/project/app.js
Restart=on-failure
[Install]
WantedBy=multi-user.target
可通过
which node查看 node 路径
sudo systemctl daemon-reload
sudo systemctl start nodeapp
sudo systemctl enable nodeapp
sudo systemctl status nodeapp
sudo systemctl restart nodeapp
sudo systemctl stop nodeapp
查看日志:
journalctl -u nodeapp -f
npm install -g pm2
pm2 start app.js --name my-app
pm2 list
pm2 restart my-app
pm2 stop my-app
pm2 logs my-app
pm2 startup
pm2 save
bash: node: command not found
解决:
which nodelsof -i :3000
kill -9 PID
| 场景 | 推荐方式 |
|---|---|
| 本地测试 | node app.js |
| 生产环境 | PM2 或 systemd |
| 需要自动重启 | PM2 |
如果你愿意,可以告诉我:
我可以给你一份完整的部署方案。