在 CentOS 上运行 Node.js 一般分三步:安装 Node.js → 写/上传代码 → 运行。
下面是最常见、最简单的做法(CentOS 7 / 8 / Stream 都适用)。
# 安装依赖
sudo yum install -y gcc-c++ make
# 添加 Node.js 源(以 18.x 为例)
curl -fsSL https://rpm.nodesource.com/setup_18.x | sudo bash -
# 安装 Node.js
sudo yum install -y nodejs
# 验证
node -v
npm -v
sudo yum install -y epel-release
sudo yum install -y nodejs
mkdir ~/nodeapp
cd ~/nodeapp
vi app.js
app.js 内容:
console.log("Hello CentOS Node.js");
node app.js
输出:
Hello CentOS Node.js
// server.js
const http = require('http');
const server = http.createServer((req, res) => {
res.end('Hello from Node.js on CentOS');
});
server.listen(3000, () => {
console.log('Server running on port 3000');
});
运行:
node server.js
访问:
http://服务器IP:3000
⚠️ 如果是云服务器,记得开放 3000 端口
nohup node server.js &
npm install -g pm2
pm2 start server.js
pm2 save
pm2 startup
说明没装好或 PATH 不对,重装 NodeSource 版本。
# 开放端口
firewall-cmd --permanent --add-port=3000/tcp
firewall-cmd --reload
如果你是想 部署项目 / 用 Nginx 反向代理 / Docker 跑 Node,可以告诉我,我可以一步步帮你配。