溫馨提示×

如何在CentOS上進行負載均衡

小樊
58
2025-04-02 22:07:51
欄目: 云計算

在CentOS上進行負載均衡可以通過多種方法實現,常見的包括使用LVS、Nginx和Haproxy等工具。以下是使用Nginx和LVS在CentOS上進行負載均衡的詳細步驟:

使用Nginx進行負載均衡

  1. 安裝Nginx
sudo yum install epel-release -y
sudo yum install nginx -y
  1. 配置Nginx以實現負載均衡

編輯Nginx配置文件,通常位于 /etc/nginx/nginx.conf/etc/nginx/conf.d/default.conf。

http {
    upstream backend {
        server backend1.example.com;
        server backend2.example.com;
        # 添加更多后端服務器
    }

    server {
        listen 80;
        server_name example.com;

        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;
        }
    }
}
  1. 啟動Nginx服務
sudo systemctl start nginx
sudo systemctl enable nginx
  1. 驗證配置

訪問服務器的IP地址和端口,查看是否能按預期進行負載均衡。

使用LVS進行負載均衡

  1. 安裝LVS
sudo yum install ipvsadm -y
  1. 配置LVS
# 清除iptables規則
sudo iptables -F
# 設置內核參數
echo "1" > /proc/sys/net/ipv4/ip_forward

# 添加虛擬服務器
sudo ipvsadm -A -t VIP:端口 -s rr

# 添加真實服務器
sudo ipvsadm -a -t VIP:端口 -r RSIP:端口 -g

其中,VIP是虛擬IP地址,RSIP是后端服務器的IP地址,端口是服務的端口號。

使用Haproxy進行負載均衡

  1. 安裝Haproxy
sudo yum install haproxy -y
  1. 配置Haproxy

編輯Haproxy配置文件,通常位于 /etc/haproxy/haproxy.cfg。

global
    log /dev/log local0
    log /dev/log local1 notice
    maxconn 4096
    tune.ssl.default-dh-param 2048

defaults
    log global
    mode http
    option httplog
    option dontlognull
    retries 3
    timeout http-request 10s
    timeout queue 1m
    timeout connect 10s
    timeout client 1m
    timeout server 1m

frontend http-in
    bind *:80
    default_backend servers

backend servers
    balance roundrobin
    server server1 192.168.0.101:80 check
    server server2 192.168.0.102:80 check
  1. 啟動Haproxy服務
sudo systemctl start haproxy
sudo systemctl enable haproxy
  1. 驗證配置

通過瀏覽器或命令行工具訪問Haproxy服務器的IP地址和端口,查看是否能按預期進行負載均衡。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女