温馨提示×

CentOS Node.js如何搭建Web服务器

小樊
35
2026-01-02 11:47:31
栏目: 云计算

在CentOS上使用Node.js搭建Web服务器是一个相对简单的过程。以下是一个基本的步骤指南:

1. 安装Node.js

首先,你需要在CentOS上安装Node.js。你可以使用NodeSource提供的Node.js二进制分发库来安装最新版本的Node.js。

使用NodeSource安装Node.js

  1. 添加NodeSource仓库

    curl -sL https://rpm.nodesource.com/setup_14.x | sudo bash -
    
  2. 安装Node.js

    sudo yum install -y nodejs
    
  3. 验证安装

    node -v
    npm -v
    

2. 创建一个简单的Web服务器

接下来,你可以创建一个简单的Web服务器来测试你的安装。

  1. 创建项目目录

    mkdir my-node-server
    cd my-node-server
    
  2. 初始化一个新的Node.js项目(可选):

    npm init -y
    
  3. 创建一个JavaScript文件

    nano server.js
    
  4. 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}/`);
    });
    
  5. 保存并关闭文件(在nano编辑器中按Ctrl+X,然后按Y确认保存,最后按Enter)。

  6. 运行服务器

    node server.js
    
  7. 访问服务器: 打开浏览器并访问 http://127.0.0.1:3000/,你应该会看到 “Hello World” 的消息。

3. 使用Express框架(可选)

如果你想要一个更强大的Web服务器,可以使用Express框架。

  1. 安装Express

    npm install express
    
  2. 修改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}/`);
    });
    
  3. 运行服务器

    node server.js
    
  4. 访问服务器: 打开浏览器并访问 http://localhost:3000/,你应该会看到 “Hello World!” 的消息。

4. 配置防火墙

确保你的防火墙允许HTTP和HTTPS流量。

sudo firewall-cmd --permanent --zone=public --add-service=http
sudo firewall-cmd --permanent --zone=public --add-service=https
sudo firewall-cmd --reload

5. 使用Nginx作为反向代理(可选)

为了提高性能和安全性,你可以使用Nginx作为Node.js应用的反向代理。

  1. 安装Nginx

    sudo yum install nginx
    
  2. 启动并启用Nginx

    sudo systemctl start nginx
    sudo systemctl enable nginx
    
  3. 配置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;
        }
    }
    
  4. 重启Nginx

    sudo systemctl restart nginx
    

现在,你的Node.js应用应该可以通过Nginx访问了。

通过以上步骤,你就可以在CentOS上成功搭建一个Node.js Web服务器。

0