温馨提示×

ubuntu怎么用nodejs写服务

小樊
48
2026-09-12 17:58:48
栏目: 编程语言

在 Ubuntu 上使用 Node.js 写服务(通常指 Web 服务 / 后端服务)一般步骤如下:


一、安装 Node.js

方式 1:使用 apt(简单,但版本可能较旧)

sudo apt update
sudo apt install nodejs npm
node -v
npm -v

方式 2:使用 NodeSource(推荐,版本新)

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

二、创建项目

mkdir my-server
cd my-server
npm init -y

三、写一个最简单的 Node.js 服务(原生 http)

1️⃣ 创建 server.js

const http = require('http');

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello from Node.js!\n');
});

server.listen(3000, () => {
  console.log('Server running at http://localhost:3000');
});

2️⃣ 运行服务

node server.js

浏览器访问:

http://localhost:3000

四、使用 Express(更常用)

安装 Express

npm install express

示例 server.js

const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.send('Hello Express!');
});

app.get('/api/user', (req, res) => {
  res.json({ name: 'Tom', age: 18 });
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

运行:

node server.js

五、让服务在后台运行

方式 1:nohup

nohup node server.js &

方式 2:PM2(推荐)

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

六、开放端口(如有防火墙)

sudo ufw allow 3000

如果是云服务器,还需在安全组放行端口。


七、示例目录结构

my-server/
├── server.js
├── package.json
└── node_modules/

如果你愿意,我可以帮你:

  • 写一个 REST API 服务
  • 用 TypeScript
  • 接 MySQL / MongoDB
  • 配置 Nginx + HTTPS
  • 写成 生产级服务

你打算用 Node.js 做什么类型的服务?

0 踩