在 Linux 上配置并启动 Node.js 项目,通常分为 安装 Node.js → 准备项目 → 配置启动方式 → 后台/生产环境运行 几个步骤。下面按常见场景给你说明。
以 Node.js 18 LTS 为例(可换版本):
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt install -y nodejs
验证:
node -v
npm -v
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
source ~/.bashrc
nvm install 18
nvm use 18
mkdir myapp
cd myapp
npm init -y
npm install express
示例 app.js:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello Node.js');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
node app.js
package.json:
{
"scripts": {
"start": "node app.js"
}
}
启动:
npm start
npm install -g pm2
pm2 start app.js
pm2 save
pm2 startup
常用命令:
pm2 list
pm2 logs
pm2 restart app
pm2 stop app
nohup node app.js > app.log 2>&1 &
查看:
tail -f app.log
创建服务文件:
sudo vim /etc/systemd/system/nodeapp.service
内容示例:
[Unit]
Description=Node.js App
After=network.target
[Service]
User=youruser
WorkingDirectory=/home/youruser/myapp
ExecStart=/usr/bin/node app.js
Restart=always
[Install]
WantedBy=multi-user.target
启动:
sudo systemctl daemon-reload
sudo systemctl start nodeapp
sudo systemctl enable nodeapp
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_set_header Host $host;
}
}
lsof -i:3000NODE_ENV=production node app.js如果你能告诉我:
我可以给你更精确的配置方案。