在CentOS上使用Node.js搭建Web服务器是一个相对简单的过程。以下是一个基本的步骤指南:
首先,你需要在CentOS上安装Node.js。你可以使用NodeSource提供的Node.js二进制分发库来安装最新版本的Node.js。
添加NodeSource仓库:
curl -sL https://rpm.nodesource.com/setup_14.x | sudo bash -
安装Node.js:
sudo yum install -y nodejs
验证安装:
node -v
npm -v
接下来,你可以创建一个简单的Web服务器来测试你的安装。
创建项目目录:
mkdir my-node-server
cd my-node-server
初始化一个新的Node.js项目(可选):
npm init -y
创建一个JavaScript文件:
nano server.js
在server.js文件中添加以下代码:
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
保存并关闭文件(在nano编辑器中按Ctrl+X,然后按Y确认保存,最后按Enter)。
运行服务器:
node server.js
访问服务器:
打开浏览器并访问 http://127.0.0.1:3000/,你应该会看到 “Hello World” 的消息。
如果你想要一个更强大的Web服务器,可以使用Express框架。
安装Express:
npm install express
修改server.js文件:
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});
运行服务器:
node server.js
访问服务器:
打开浏览器并访问 http://localhost:3000/,你应该会看到 “Hello World!” 的消息。
确保你的防火墙允许HTTP和HTTPS流量。
sudo firewall-cmd --permanent --zone=public --add-service=http
sudo firewall-cmd --permanent --zone=public --add-service=https
sudo firewall-cmd --reload
为了提高性能和安全性,你可以使用Nginx作为Node.js应用的反向代理。
安装Nginx:
sudo yum install nginx
启动并启用Nginx:
sudo systemctl start nginx
sudo systemctl enable nginx
配置Nginx:
编辑Nginx配置文件 /etc/nginx/nginx.conf 或创建一个新的配置文件 /etc/nginx/conf.d/default.conf:
server {
listen 80;
server_name your_domain.com;
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
重启Nginx:
sudo systemctl restart nginx
现在,你的Node.js应用应该可以通过Nginx访问了。
通过以上步骤,你就可以在CentOS上成功搭建一个Node.js Web服务器。