1. Configure nginx

Modify the configuration file conf/nginx.conf

  • Join the upstream node.
Upstream {server 127.0.0.1:8081; Server 127.0.0.1:8082; Server address 2}Copy the code
  • Example Change the listening port number 80 to 8080.
server { listen 8080; . }Copy the code
  • Configure the proxy_pass reverse proxy address in location as defined in upstream in the first step.
location / { root html; index index.html index.htm; proxy_pass http://nginxDemo; # configure direction proxy address}Copy the code

2. Load policies

  • Polling (default)

Each Web request is allocated to a different backend server one by one in chronological order. If the backend server goes down, it is automatically removed.

Upstream {server 127.0.0.1:8081; Server 127.0.0.1:8082; }Copy the code
  • The minimum link

Web requests are forwarded to the server with the fewest connections.

upstream nginxDemo {
    least_conn;
    server 127.0.0.1:8081;
    server 127.0.0.1:8082;
}
Copy the code
  • Weight weight

Specifies the polling probability. Weight is proportional to the access ratio and is used when the back-end server performance is uneven. Weight defaults to 1

The access ratio between server A and server B is 2-1. For example, if there are three requests, the first two will visit A and three will visit B. The other rules are the same as polling. Upstream {server 127.0.0.1:8081 weight=2; Server A 127.0.0.1:8082; # server B}Copy the code
  • ip_hash

Each request is allocated according to the hash value of the access IP address. In this way, consecutive Web requests from the same client are distributed to the same server for processing, which can solve the session problem. When the background server is down, the system automatically switches to another server.

upstream nginxDemo { ip_hash; Server 127.0.0.1:8081 weight = 2; Server A 127.0.0.1:8082; # server B}Copy the code