Nginx 不僅僅是一個高效能的網頁伺服器;它同時也是一個強大的反向代理和負載平衡器。與其將所有使用者流量導向單一後端伺服器,負載平衡將工作負載分散到一組伺服器叢集中,確保高可用性和在高負載下的更佳效能。
本指南將引導您完成使用兩個或多個後端伺服器設定穩健負載平衡環境所需的基本 Nginx 配置步驟。
前提條件
您應該已經有一個正常運作的 Nginx 安裝,以及至少兩台正在運行的後端應用程式伺服器。
- 後端伺服器 1:
192.168.22.238 - 後端伺服器 2:
192.168.22.239(我們正在新增的伺服器)
核心概念:upstream 模組
要在 Nginx 中啟用負載平衡,您必須使用 upstream 指令定義後端伺服器池。此指令將伺服器分組,並告訴 Nginx 如何將它們視為一個整體。
您需要將 upstream 區塊放置在 Nginx 配置檔案的 http 區塊內(例如 /etc/nginx/nginx.conf 或 /etc/nginx/conf.d/ 中的檔案)。
步驟 1:定義上游伺服器群組
定義您的伺服器群組,並給它一個描述性的名稱,例如 backend_servers。
Nginx
http {
# --- 上游定義 ---
upstream backend_servers {
server 192.168.22.238; # 第一台後端伺服器
server 192.168.22.239; # 第二台後端伺服器
# 如需要可在此添加更多伺服器...
}
server {
# ... 您的伺服器配置將放在這裡 ...
}
}
步驟 2:將請求代理到上游群組
接下來,在您的 server 區塊和目標 location 區塊(本例中為 location /)內,您需要修改 proxy_pass 指令,使其指向上游群組名稱而非固定的 IP 位址。
原始配置為:
Nginx
location / {
proxy_pass http://192.168.22.238;
}
新的負載平衡配置為:
Nginx
server {
listen 80;
server_name example.com; # 您的網域或 IP
location / {
proxy_pass http://backend_servers; # 注意:指向上游名稱!
# 選用:反向代理的標準最佳實務
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
負載平衡方法(演算法)
預設情況下,Nginx 使用輪詢(Round Robin)演算法,將請求依序分配給各伺服器。然而,您可以透過在 upstream 區塊內添加簡單的指令來選擇其他策略:
| 演算法 | Nginx 指令 | 說明 | 使用場景 |
| 輪詢 | (預設) | 請求以輪轉序列均等分配。 | 通用型、無狀態服務。 |
| 加權 | server IP **weight=N**; | 根據伺服器定義的容量(權重)分配請求。權重越高,流量越多。 | 當後端伺服器處理能力不均時。 |
| 最少連接 | **least_conn;** | 請求被路由到活動連接數最少的伺服器。 | 長時間連接、請求時間差異大。 |
| IP 雜湊 | **ip_hash;** | 根據客戶端 IP 位址選擇伺服器。確保同一客戶端始終被導向同一伺服器。 | 需要維護會話持久性(黏性會話)時。 |
範例:加權負載平衡
使用 weight 將更多流量導向效能更強的伺服器(例如,伺服器 1 獲得 2/3 的流量):
Nginx
upstream backend_servers {
server 192.168.22.238 weight=2;
server 192.168.22.239 weight=1;
}
範例:最少連接
使用 least_conn 根據當前工作負載進行更智慧的分配:
Nginx
upstream backend_servers {
least_conn;
server 192.168.22.238;
server 192.168.22.239;
}
步驟 3:測試並套用配置
修改 Nginx 配置檔案後:
- 測試語法:在套用之前,務必執行測試以捕捉任何錯誤:Bash
sudo nginx -t - 重新載入 Nginx:如果測試成功,重新載入服務以套用新的負載平衡配置,且不會中斷現有連接:Bash
sudo nginx -s reload # 或 sudo systemctl reload nginx
您現在已成功配置 Nginx 在兩台(或更多)後端伺服器之間進行負載平衡流量,大幅提升了應用程式的擴展性和容錯能力。
English Version
Nginx is not just a high-performance web server; it’s also a powerful reverse proxy and load balancer. Instead of directing all user traffic to a single backend server, load balancing distributes the workload across a cluster of servers, ensuring high availability and better performance under heavy load.
This guide will walk you through the essential Nginx configuration steps to set up a robust load balancing environment using two or more backend servers.
Prerequisites
You should have a working Nginx installation and at least two backend application servers running.
- Backend Server 1:
192.168.22.238 - Backend Server 2:
192.168.22.239(The new server we are adding)
The Core Concept: The upstream Module
To enable load balancing in Nginx, you must define a pool of backend servers using the upstream directive. This directive groups the servers and tells Nginx how to treat them as a single entity.
You will place the upstream block within the http block of your Nginx configuration file (e.g., /etc/nginx/nginx.conf or a file in /etc/nginx/conf.d/).
Step 1: Define the Upstream Server Group
Define your server group and give it a descriptive name, such as backend_servers.
Nginx
http {
# --- UPSTREAM DEFINITION ---
upstream backend_servers {
server 192.168.22.238; # First Backend Server
server 192.168.22.239; # Second Backend Server
# Add more servers here if needed...
}
server {
# ... Your server configuration will go here ...
}
}
Step 2: Proxy Requests to the Upstream Group
Next, inside your server block and the target location block (location / in this case), you will modify the proxy_pass directive to point to the upstream group name instead of a fixed IP address.
The original configuration was:
Nginx
location / {
proxy_pass http://192.168.22.238;
}
The new Load Balanced configuration is:
Nginx
server {
listen 80;
server_name example.com; # Your domain or IP
location / {
proxy_pass http://backend_servers; # Note: Pointing to the upstream name!
# Optional: Standard best practices for reverse proxying
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
Load Balancing Methods (Algorithms)
By default, Nginx uses the Round Robin algorithm, where requests are distributed sequentially across the servers. However, you can choose from several other strategies by adding a simple directive inside the upstream block:
| Algorithm | Nginx Directive | Description | Use Case |
| Round Robin | (Default) | Requests are distributed equally in a rotating sequence. | General purpose, stateless services. |
| Weighted | server IP **weight=N**; | Requests are distributed based on a server’s defined capacity (weight). Higher weight gets more traffic. | When backend servers have uneven processing power. |
| Least Connected | **least_conn;** | A request is routed to the server that has the fewest active connections. | Long-running connections, highly variable request times. |
| IP Hash | **ip_hash;** | The server is chosen based on the client’s IP address. This ensures the same client is always sent to the same server. | Necessary for maintaining Session Persistence (sticky sessions). |
Example: Weighted Load Balancing
Use weight to send more traffic to a more powerful server (e.g., Server 1 gets 2/3 of the traffic):
Nginx
upstream backend_servers {
server 192.168.22.238 weight=2;
server 192.168.22.239 weight=1;
}
Example: Least Connected
Use least_conn for more intelligent distribution based on current workload:
Nginx
upstream backend_servers {
least_conn;
server 192.168.22.238;
server 192.168.22.239;
}
Step 3: Test and Apply Configuration
After making changes to your Nginx configuration file:
- Test the syntax: Always run a test to catch any errors before applying:Bash
sudo nginx -t - Reload Nginx: If the test is successful, reload the service to apply the new load balancing configuration without dropping connections:Bash
sudo nginx -s reload # OR sudo systemctl reload nginx
You have now successfully configured Nginx to load balance traffic across two (or more) backend servers, dramatically improving your application’s scalability and fault tolerance.
日本語版
Nginx は高性能な Web サーバーであるだけでなく、強力なリバースプロキシおよびロードバランサーでもあります。すべてのユーザートラフィックを単一のバックエンドサーバーに振り向ける代わりに、ロードバランシングはワークロードをサーバークラスター全体に分散し、高可用性と高負荷時のパフォーマンス向上を実現します。
本ガイドでは、2台以上のバックエンドサーバーを使用して堅牢なロードバランシング環境を構築するための、Nginx の基本的な設定手順を説明します。
前提条件
動作する Nginx のインストールと、少なくとも2台の稼働中のバックエンドアプリケーションサーバーが必要です。
- バックエンドサーバー 1:
192.168.22.238 - バックエンドサーバー 2:
192.168.22.239(新たに追加するサーバー)
コアコンセプト:upstream モジュール
Nginx でロードバランシングを有効にするには、upstream ディレクティブを使用してバックエンドサーバーのプールを定義する必要があります。このディレクティブはサーバーをグループ化し、Nginx にそれらを単一のエンティティとして扱う方法を指示します。
upstream ブロックは、Nginx 設定ファイルの http ブロック内に配置します(例:/etc/nginx/nginx.conf または /etc/nginx/conf.d/ 内のファイル)。
ステップ 1:アップストリームサーバーグループの定義
サーバーグループを定義し、backend_servers のような説明的な名前を付けます。
Nginx
http {
# --- アップストリーム定義 ---
upstream backend_servers {
server 192.168.22.238; # 第1バックエンドサーバー
server 192.168.22.239; # 第2バックエンドサーバー
# 必要に応じてサーバーを追加...
}
server {
# ... サーバー設定をここに記述 ...
}
}
ステップ 2:アップストリームグループへのリクエストプロキシ
次に、server ブロック内のターゲット location ブロック(ここでは location /)で、proxy_pass ディレクティブを固定 IP アドレスではなくアップストリームグループ名を指すように変更します。
元の設定:
Nginx
location / {
proxy_pass http://192.168.22.238;
}
新しいロードバランシング設定:
Nginx
server {
listen 80;
server_name example.com; # ドメインまたは IP
location / {
proxy_pass http://backend_servers; # 注意:アップストリーム名を指定!
# オプション:リバースプロキシの標準的なベストプラクティス
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
ロードバランシング方式(アルゴリズム)
デフォルトでは、Nginx はラウンドロビンアルゴリズムを使用し、リクエストをサーバーに順番に分配します。ただし、upstream ブロック内にシンプルなディレクティブを追加することで、他の戦略を選択できます:
| アルゴリズム | Nginx ディレクティブ | 説明 | 使用シーン |
| ラウンドロビン | (デフォルト) | リクエストがローテーション方式で均等に分配されます。 | 汎用、ステートレスサービス。 |
| 重み付け | server IP **weight=N**; | サーバーに定義された容量(重み)に基づいてリクエストが分配されます。重みが高いほどトラフィックが多くなります。 | バックエンドサーバーの処理能力が不均一な場合。 |
| 最小接続 | **least_conn;** | リクエストはアクティブな接続が最も少ないサーバーにルーティングされます。 | 長時間接続、リクエスト時間のばらつきが大きい場合。 |
| IP ハッシュ | **ip_hash;** | クライアントの IP アドレスに基づいてサーバーが選択されます。同じクライアントが常に同じサーバーに送信されることを保証します。 | セッション永続性(スティッキーセッション)の維持が必要な場合。 |
例:重み付けロードバランシング
weight を使用して、より強力なサーバーに多くのトラフィックを送信します(例:サーバー 1 がトラフィックの 2/3 を受信):
Nginx
upstream backend_servers {
server 192.168.22.238 weight=2;
server 192.168.22.239 weight=1;
}
例:最小接続
現在のワークロードに基づいてよりインテリジェントに分配するには least_conn を使用します:
Nginx
upstream backend_servers {
least_conn;
server 192.168.22.238;
server 192.168.22.239;
}
ステップ 3:設定のテストと適用
Nginx 設定ファイルを変更した後:
- 構文テスト:適用前に必ずテストを実行してエラーを検出してください:Bash
sudo nginx -t - Nginx のリロード:テストが成功したら、接続を切断することなくサービスをリロードして新しいロードバランシング設定を適用します:Bash
sudo nginx -s reload # または sudo systemctl reload nginx
これで、2台(またはそれ以上)のバックエンドサーバー間でトラフィックをロードバランスするように Nginx を正常に設定し、アプリケーションのスケーラビリティと耐障害性を大幅に向上させました。
