在 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 應用程序。