温馨提示×

centos怎么跑起nodejs

小樊
40
2026-09-08 21:10:34
栏目: 编程语言

在 CentOS 上跑起 Node.js,一般分 安装 Node.js → 写/部署代码 → 运行 三步。下面给你几种常见、实用的方式。


一、安装 Node.js(推荐用 NodeSource,版本新)

1️⃣ 使用 NodeSource 安装(推荐)

# 以 Node.js 18 为例
curl -fsSL https://rpm.nodesource.com/setup_18.x | sudo bash -
sudo yum install -y nodejs

验证:

node -v
npm -v

2️⃣ 用 CentOS 自带 yum(版本较老)

sudo yum install -y nodejs npm

⚠️ CentOS 7 默认版本可能很旧(v6/v8),不推荐生产用


3️⃣ 用 nvm(适合开发、多版本)

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

二、跑一个简单的 Node.js 程序

1️⃣ 写个测试文件

mkdir ~/nodeapp
cd ~/nodeapp
vim app.js

app.js

const http = require('http');

const server = http.createServer((req, res) => {
  res.end('Hello CentOS Node.js');
});

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

2️⃣ 直接运行

node app.js

浏览器或 curl 访问:

curl http://localhost:3000

三、防火墙 & 外网访问

开放端口(CentOS 7)

sudo firewall-cmd --permanent --add-port=3000/tcp
sudo firewall-cmd --reload

云服务器还要在 安全组 放行端口。


四、后台运行(生产常用)

方式 1:nohup

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

方式 2:PM2(强烈推荐)

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

五、用 Nginx 反代(常见生产架构)

server {
  listen 80;
  server_name example.com;

  location / {
    proxy_pass http://127.0.0.1:3000;
  }
}

常见问题

node: command not found → 没装或 PATH 不对
❌ 外网访问不了 → 防火墙 / 安全组 / 监听地址
❌ CentOS 8 停止维护 → 建议用 Rocky / Alma / Ubuntu


如果你愿意,可以告诉我:

  • CentOS 版本(7 / 8 / Stream)
  • 用途(学习 / 生产 / 接口 / 前端构建)
  • 是否用 Docker

我可以直接给你一套最合适的具体方案

0