在 CentOS 上配置 Nginx 以支持 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
接下来,安装 Nginx。
sudo yum install -y epel-release
sudo yum install -y nginx
启动 Nginx 并设置它在系统启动时自动启动。
sudo systemctl start nginx
sudo systemctl enable 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;
}
}
保存并关闭配置文件后,重启 Nginx 以应用更改。
sudo systemctl restart nginx
确保你的 Node.js 应用程序正在运行。例如,如果你使用的是 Express,可以这样启动:
node app.js
打开浏览器并访问你的域名或 IP 地址。你应该能够看到你的 Node.js 应用程序的响应。
如果你的服务器启用了防火墙,确保允许 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 应用程序。