温馨提示×

ubuntu nodejs怎样写服务

小樊
39
2026-10-09 18:17:34
栏目: 编程语言

在 Ubuntu 上用 Node.js 写服务,通常是指用 Node 启动一个HTTP 服务 / API 服务,并让它在服务器上稳定运行。下面从安装 → 写服务 → 运行 → 守护进程一步步说明。


一、安装 Node.js(Ubuntu)

1️⃣ 使用官方源(推荐)

curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs

验证:

node -v
npm -v

二、写一个简单的 Node.js 服务

示例 1:原生 http 服务

// 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

示例 2:使用 Express(更常用)

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');
});

三、让服务在后台运行

1️⃣ 使用 pm2(最推荐)

sudo npm install -g pm2
pm2 start app.js
pm2 save
pm2 startup

常用命令:

pm2 list
pm2 logs
pm2 restart app
pm2 stop app

✅ 服务器重启后自动运行


2️⃣ 使用 systemd(生产级)

创建服务文件:

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

如果你告诉我:

  • 是 Web 服务 / API / 爬虫 / WebSocket
  • 是否需要 公网访问
  • Ubuntu 版本

我可以给你一份完整可直接用的模板。

0 踩