centos

CentOS 上 Node.js 怎么配置 Nginx

小樊
45
2025-06-24 09:28:56
栏目: 编程语言

在 CentOS 上配置 Nginx 以支持 Node.js 应用程序涉及几个步骤。以下是一个基本的指南,帮助你完成这个过程:

1. 安装 Node.js

首先,你需要在 CentOS 上安装 Node.js。你可以使用 NodeSource 提供的安装脚本来安装特定版本的 Node.js。

# 添加 NodeSource 仓库
curl -sL https://rpm.nodesource.com/setup_14.x | sudo bash -

# 安装 Node.js
sudo yum install -y nodejs

2. 安装 Nginx

接下来,安装 Nginx。

sudo yum install -y epel-release
sudo yum install -y nginx

3. 启动并启用 Nginx

启动 Nginx 并设置它在系统启动时自动启动。

sudo systemctl start nginx
sudo systemctl enable nginx

4. 配置 Nginx

编辑 Nginx 配置文件以将请求转发到你的 Node.js 应用程序。通常,Nginx 配置文件位于 /etc/nginx/nginx.conf/etc/nginx/conf.d/default.conf

sudo vi /etc/nginx/conf.d/default.conf

server 块中添加以下内容:

server {
    listen 80;
    server_name your_domain.com;  # 替换为你的域名或 IP 地址

    location / {
        proxy_pass http://localhost:3000;  # 替换为你的 Node.js 应用程序的端口
        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;
    }
}

5. 重启 Nginx

保存并关闭配置文件后,重启 Nginx 以应用更改。

sudo systemctl restart nginx

6. 启动 Node.js 应用程序

确保你的 Node.js 应用程序正在运行。例如,如果你使用的是 Express,可以这样启动:

node app.js

7. 测试配置

打开浏览器并访问你的域名或 IP 地址。你应该能够看到你的 Node.js 应用程序的响应。

8. 防火墙设置

如果你的服务器启用了防火墙,确保允许 HTTP 和 HTTPS 流量。

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

通过以上步骤,你应该能够在 CentOS 上成功配置 Nginx 以支持 Node.js 应用程序。

0
看了该问题的人还看了