使用 nginx 和 IIS 在单个服务器上测试负载平衡

Test load balancing on single server with nginx and IIS

我想用 nginx 和 IIS 在单个服务器上测试负载平衡。 我将 nginx 设置为监听 localhost:90 并将 IIS 上的两个网站设置为监听 localhost:81 和 localhost:82

这是我的 nginx.conf:

events {
worker_connections  1024;
}

http {
  upstream backend {
    server localhost:81;
    server localhost:82;
  }

  server {
    listen 90;
    server_name backend;
    location / {
      proxy_pass http://localhost:80;
    }
  }
}

当我在浏览器上打开 http://localhost:90 时 returns 504 网关超时。

实际上请求将发送到端口 80(我在 proxy_pass 中设置)而不是端口 81 和 82

我知道负载平衡适用于有多台服务器。 但是有什么方法可以在多端口的单台服务器上测试负载平衡吗?

将您的配置更改为:

events {
worker_connections  1024;
}

http {
  upstream backend {
    server localhost:81;
    server localhost:82;
  }

  server {
    listen 90;
    server_name _;
    location / {
      proxy_pass http://backend;
    }
  }
}

现在在端口 90 上打开本地主机

解释:

要使用 http 块中指定的上游,您需要使用其名称。

proxy_pass http://backend;

做反向代理时设置如下headers也是一个好习惯(这样后端获取客户端信息而不是反向代理服务器):

proxy_set_header   X-Real-IP        $remote_addr;
proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
proxy_set_header   X-Forwarded-User  $remote_user;