在 Ubuntu 上用 Node.js 写服务,通常是指用 Node 启动一个HTTP 服务 / API 服务,并让它在服务器上稳定运行。下面从安装 → 写服务 → 运行 → 守护进程一步步说明。
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs
验证:
node -v
npm -v
// server.js
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: 'Hello from Node.js' }));
});
server.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
运行:
node server.js
访问:
curl http://localhost:3000
npm init -y
npm install express
// app.js
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.json({ message: 'Hello Express' });
});
app.listen(3000, () => {
console.log('Express server on port 3000');
});
pm2(最推荐)sudo npm install -g pm2
pm2 start app.js
pm2 save
pm2 startup
常用命令:
pm2 list
pm2 logs
pm2 restart app
pm2 stop app
✅ 服务器重启后自动运行
创建服务文件:
sudo nano /etc/systemd/system/node.service
内容示例:
[Unit]
Description=Node.js Service
After=network.target
[Service]
ExecStart=/usr/bin/node /home/ubuntu/app.js
WorkingDirectory=/home/ubuntu
User=ubuntu
Restart=always
[Install]
WantedBy=multi-user.target
启用:
sudo systemctl daemon-reexec
sudo systemctl enable node
sudo systemctl start node
查看状态:
sudo systemctl status node
| 类型 | 技术 |
|---|---|
| HTTP API | Express / Fastify |
| WebSocket | socket.io |
| 定时任务 | node-cron |
| 微服务 | NestJS |
project/
├── app.js
├── routes/
├── controllers/
├── package.json
└── .env
如果你告诉我:
我可以给你一份完整可直接用的模板。