在 CentOS 上配置 Nginx 實現高效負載均衡需要遵循以下步驟:
首先,確保您的 CentOS 系統已更新。然后,安裝 Nginx 和 keepalived 軟件包:
sudo yum update
sudo yum install epel-release
sudo yum install nginx keepalived
編輯 Nginx 配置文件(通常位于 /etc/nginx/nginx.conf 或 /etc/nginx/conf.d/default.conf),并添加以下內容:
http {
upstream backend {
server backend1.example.com;
server backend2.example.com;
server backend3.example.com;
}
server {
listen 80;
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
}
在此示例中,我們定義了一個名為 “backend” 的服務器組,其中包含三個后端服務器。然后,我們將所有傳入的請求代理到該組中的服務器。
創建一個名為 /etc/keepalived/keepalived.conf 的文件,并添加以下內容:
vrrp_instance VI_1 {
state MASTER
interface eth0
virtual_router_id 51
priority 100
authentication {
auth_type PASS
auth_pass 1234
}
virtual_ipaddress {
192.168.1.100
}
}
在此示例中,我們將 VRRP 實例的狀態設置為 MASTER,并將其綁定到 eth0 網絡接口。我們還定義了一個虛擬路由器 ID 和優先級。最后,我們配置了簡單的密碼身份驗證和虛擬 IP 地址。
啟動 Nginx 和 keepalived 服務,并將它們設置為開機啟動:
sudo systemctl start nginx
sudo systemctl enable nginx
sudo systemctl start keepalived
sudo systemctl enable keepalived
現在,您已經在 CentOS 上配置了 Nginx 和 keepalived,以實現高效負載均衡。請注意,您需要根據實際情況替換示例配置文件中的服務器名稱、IP地址和端口。