温馨提示×

debian下nodejs如何启动服务

小樊
45
2026-09-07 16:10:51
栏目: 编程语言

在 Debian 下启动 Node.js 服务,通常有几种常见方式,从最简单生产环境推荐依次说明:


一、最基础方式(直接运行)

1. 安装 Node.js

sudo apt update
sudo apt install nodejs npm

查看版本:

node -v

2. 运行 Node 脚本

假设你的文件是 app.js

node app.js

如果是 Web 服务(如 Express):

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

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

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

启动:

node app.js

访问:

http://服务器IP:3000

⚠️ 缺点:关闭终端服务就停了


二、后台运行(不推荐长期使用)

使用 &

node app.js &

使用 nohup

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

查看进程:

ps aux | grep node

三、使用 PM2(推荐 ✅)

1. 安装 PM2

sudo npm install -g pm2

2. 启动服务

pm2 start app.js

3. 常用命令

pm2 list
pm2 logs
pm2 restart app
pm2 stop app
pm2 delete app

4. 开机自启

pm2 startup
pm2 save

✅ 适合生产环境


四、使用 systemd(服务器标准方式 ✅✅)

1. 创建服务文件

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

示例内容:

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

[Service]
User=www-data
WorkingDirectory=/var/www/nodeapp
ExecStart=/usr/bin/node /var/www/nodeapp/app.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

五、使用 Nginx 反向代理(常见架构)

server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
    }
}

总结建议

场景 推荐方式
学习/测试 node app.js
简单后台 nohup
生产环境 PM2 / systemd
公网访问 Node + Nginx

如果你是 Debian 11 / 12,或者用的是 Docker / 宝塔,可以告诉我,我可以给你更具体的方案。

0