溫馨提示×

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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女