Nginx 负载均衡是一种将请求分发到多个服务器的方法,以提高应用程序的可用性和性能。以下是关于 Nginx 负载均衡的简要介绍。

什么是负载均衡?

负载均衡是将多个服务器的处理能力合并起来,以处理更多的请求。这样做可以:

  • 提高应用程序的可用性
  • 提高应用程序的性能
  • 提高应用程序的可伸缩性

Nginx 负载均衡配置

Nginx 提供了多种负载均衡策略,包括轮询、最少连接、IP哈希等。

轮询

轮询是最简单的负载均衡策略,它会将请求均匀地分发到每个服务器。

http {
    upstream myapp {
        server server1.example.com;
        server server2.example.com;
        server server3.example.com;
    }

    server {
        location / {
            proxy_pass http://myapp;
        }
    }
}

最少连接

最少连接策略会将请求发送到当前连接数最少的服务器。

http {
    upstream myapp {
        least_conn;
        server server1.example.com;
        server server2.example.com;
        server server3.example.com;
    }

    server {
        location / {
            proxy_pass http://myapp;
        }
    }
}

IP哈希

IP哈希策略会根据客户端的 IP 地址将请求分发到特定的服务器。

http {
    upstream myapp {
        ip_hash;
        server server1.example.com;
        server server2.example.com;
        server server3.example.com;
    }

    server {
        location / {
            proxy_pass http://myapp;
        }
    }
}

扩展阅读

更多关于 Nginx 负载均衡的信息,请参阅 Nginx 官方文档


Nginx Load Balancing