温馨提示×

linux nodejs怎么配置启动

小樊
55
2026-10-16 00:20:21
栏目: 编程语言

在 Linux 上配置并启动 Node.js 项目,通常分为 安装 Node.js → 准备项目 → 配置启动方式 → 后台/生产环境运行 几个步骤。下面按常见场景给你说明。


一、安装 Node.js(Linux)

方式 1:使用 NodeSource(推荐)

以 Node.js 18 LTS 为例(可换版本):

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

验证:

node -v
npm -v

方式 2:使用 nvm(适合开发)

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
source ~/.bashrc
nvm install 18
nvm use 18

二、准备 Node.js 项目

mkdir myapp
cd myapp
npm init -y
npm install express

示例 app.js:

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

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

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

三、本地启动 Node.js

1️⃣ 直接启动

node app.js

2️⃣ 使用 npm scripts

package.json:

{
  "scripts": {
    "start": "node app.js"
  }
}

启动:

npm start

四、后台运行(生产环境)

✅ 方式 1:PM2(最常用)

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

常用命令:

pm2 list
pm2 logs
pm2 restart app
pm2 stop app

✅ 方式 2:nohup(简单)

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

查看:

tail -f app.log

五、使用 systemd(服务器推荐)

创建服务文件:

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

内容示例:

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

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

[Install]
WantedBy=multi-user.target

启动:

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

六、Nginx 反向代理(可选)

server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_set_header Host $host;
    }
}

七、常见问题

  • 端口占用:lsof -i:3000
  • 权限问题:避免用 root 跑 node
  • 环境变量:NODE_ENV=production node app.js

如果你能告诉我:

  • 是 开发环境还是生产服务器
  • 是否使用 Express / Nest / Koa
  • 是否用 Docker

我可以给你更精确的配置方案。

0 踩