温馨提示×

Nodejs在Ubuntu如何启动

小樊
37
2026-08-22 03:40:18
栏目: 编程语言

在 Ubuntu 上启动 Node.js,通常有以下几种常见方式,按使用场景从简单到复杂说明:


一、直接运行 Node.js 脚本(最常用)

1. 确认 Node.js 已安装

node -v
npm -v

如果未安装,可先安装:

sudo apt update
sudo apt install nodejs npm

或安装指定版本(推荐):

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

2. 创建并运行 Node.js 程序

mkdir test-node
cd test-node
nano app.js

app.js 示例:

console.log("Hello Node.js");

运行:

node app.js

二、启动 Web 服务(如 Express)

1. 初始化项目

mkdir myapp
cd myapp
npm init -y

2. 安装 Express

npm install express

3. 创建 server.js

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

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

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});

4. 启动服务

node server.js

浏览器访问:

http://localhost:3000

三、后台运行 Node.js(生产环境常用)

方式 1:使用 nohup

nohup node server.js > app.log 2>&1 &

查看日志:

tail -f app.log

方式 2:使用 pm2(强烈推荐)

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

常用命令:

pm2 list
pm2 restart server
pm2 logs

四、使用 systemd 作为系统服务(服务器常用)

1. 创建服务文件

sudo nano /etc/systemd/system/nodeapp.service

内容示例:

[Unit]
Description=Node.js App
After=network.target

[Service]
User=ubuntu
WorkingDirectory=/home/ubuntu/myapp
ExecStart=/usr/bin/node /home/ubuntu/myapp/server.js
Restart=always

[Install]
WantedBy=multi-user.target

2. 启动服务

sudo systemctl daemon-reload
sudo systemctl start nodeapp
sudo systemctl enable nodeapp

查看状态:

sudo systemctl status nodeapp

总结

场景 推荐方式
本地测试 node app.js
Web 服务 Express + node server.js
生产后台运行 pm2
系统级服务 systemd

如果你能说明是 本地开发 / 服务器部署 / Docker / 云服务器,我可以给你更具体的启动方案。

0