在CentOS上启动Node.js服务,你需要遵循以下步骤:
curl -sL https://rpm.nodesource.com/setup_14.x | sudo bash -
sudo yum install -y nodejs
这里我们安装的是Node.js 14.x版本,你可以根据需要选择其他版本。
app.js
的文件,并添加以下内容:const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World\n');
});
const port = 3000;
server.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});
这个简单的Node.js应用程序将在端口3000上监听请求,并返回"Hello World"。
node app.js
现在,你的Node.js服务应该在端口3000上运行。你可以通过访问http://localhost:3000
来验证服务是否正常运行。
sudo npm install -g pm2
pm2 start app.js --name my-node-app
这里我们为应用程序指定了一个名称my-node-app
,方便以后管理。
pm2 status
startup
子命令生成一个启动脚本:pm2 startup
按照提示操作,完成设置。
pm2 save
现在,你的Node.js服务已经成功启动,并在CentOS上运行。