How to configure load balancing strategy in nginx?

Configuring load balancing strategies in Nginx can be achieved by using the upstream module. Here is a simple configuration example:

  1. URL
http {
    upstream myapp {
        server backend1.example.com;
        server backend2.example.com;
        server backend3.example.com;
    }

    server {
        listen 80;
        server_name myapp.example.com;

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

In the above configuration, the upstream defines a load balancing group named myapp, which includes the addresses of 3 backend servers.

  1. host
  2. forward requests to
  3. the application

After this configuration, Nginx will forward requests to each backend server using a specific load balancing strategy. The default strategy is round-robin, meaning each request is evenly distributed to each backend server.

Nginx also supports other load balancing strategies, which can be implemented by adding keywords like “least_conn” and “ip_hash” in the upstream block. For example:

upstream myapp {
    least_conn;
    server backend1.example.com;
    server backend2.example.com;
    server backend3.example.com;
}

The above configuration utilizes the least_conn strategy, which sends requests to the backend server with the fewest number of connections.

In addition to the basic configurations mentioned above, more complex configurations can be implemented based on actual needs, such as adding weight, health checks, failover, and other functions. Specific configuration methods can be found in the official Nginx documentation or other related documents.

广告
Closing in 10 seconds
bannerAds