在 Ubuntu 上运行 Node.js 程序一般分为 安装 Node.js → 编写/获取程序 → 运行 几个步骤。下面给你一个从零开始的完整说明。
sudo apt update
sudo apt install nodejs npm
检查是否安装成功:
node -v
npm -v
以 Node.js 20 为例:
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs
mkdir ~/node-test
cd ~/node-test
nano app.js
写入以下内容:
console.log("Hello Node.js on Ubuntu!");
保存并退出(Ctrl + O,Enter,Ctrl + X)
node app.js
输出:
Hello Node.js on Ubuntu!
mkdir myapp
cd myapp
npm init -y
npm install express
创建 index.js:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello from Express!');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
运行:
node index.js
浏览器访问:
http://localhost:3000
nohupnohup node app.js &
pm2(推荐)sudo npm install -g pm2
pm2 start app.js
pm2 startup
pm2 save
sudo nano /etc/systemd/system/nodeapp.service
内容示例:
[Unit]
Description=Node.js App
After=network.target
[Service]
ExecStart=/usr/bin/node /home/ubuntu/node-test/app.js
WorkingDirectory=/home/ubuntu/node-test
User=ubuntu
Restart=always
[Install]
WantedBy=multi-user.target
启用:
sudo systemctl daemon-reload
sudo systemctl start nodeapp
sudo systemctl enable nodeapp
如果你有 具体的 Node.js 项目类型(如 Vue、React、NestJS、后端 API),我可以给你更针对性的运行方式。