Yarp 反向代理 - 响应 502 错误网关

Posted

技术标签:

【中文标题】Yarp 反向代理 - 响应 502 错误网关【英文标题】:Yarp Reverse Proxy - Response 502 Bad Gateway 【发布时间】:2021-11-01 06:20:20 【问题描述】:

我想使用 Yarp 实现反向代理。 Api 已启动并正在运行,因为我可以向它发送请求。但是,每当我通过代理尝试相同的请求时,我都会收到错误 502 Bad gateway

Startup.cs

public void ConfigureServices(IServiceCollection services)

    services.AddReverseProxy()
     .LoadFromConfig(Configuration.GetSection("ReverseProxy"));


public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

    if (env.IsDevelopment())
    
        app.UseDeveloperExceptionPage();
    
    app.UseRouting();
    // Register the reverse proxy routes
    app.UseEndpoints(endpoints =>
    
        endpoints.MapReverseProxy();
    );

应用设置

"ReverseProxy": 
    "Routes": 
      "route1": 
        "ClusterId": "cluster1",
        "Match": 
          //"Methods": [ "GET", "POST", "PUT", "HEAD", "OPTIONS", "DELETE" ],
          "Path": "**catch-all"
        
      
    ,
    "Clusters": 
      "cluster1": 
        "Destinations": 
          "cluster1/destination1": 
            "Address": "https://localhost:44339/"
          
        
      
    
  

每当我通过代理发送请求时,我都会收到响应 502 bad gateway

【问题讨论】:

【参考方案1】:

您应该点击output并选择ProjectName-Asp.Net Core Web Server查看详细信息。

我使用您的代码并附加了另一个设置,并检查了日志,我发现原因是 http://localhost:44339 没有启动。它应该在本地使用另一个 webapp 的端口。


  "Logging": 
    "LogLevel": 
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    
  ,
  //"AllowedHosts": "*"

  "ReverseProxy": 
    "Routes": [
      
        "ClusterId": "cluster1",
        "Match": 
          //"Methods": [ "GET", "POST", "PUT", "HEAD", "OPTIONS", "DELETE" ],
          "Path": "**catch-all"
        
      ,
      
        // matches /something/* and routes to 2 external addresses
        "ClusterId": "cluster2",
        "Match": 
          "Path": "/something/*any"
        
      
    ],
  "Clusters": 
      "cluster1": 
        "Destinations": 
          "cluster1/destination1": 
            "Address": "http://localhost:44339/"
          
        
      ,
      "cluster2": 
        "Destinations": 
          "first_destination": 
            "Address": "https://baidu.com"
          ,
          "another_destination": 
            "Address": "https://bing.com"
          
        ,
        "LoadBalancingPolicy": "PowerOfTwoChoices"
      

    
  

测试结果

默认:https://localhost:44370

https://localhost:44370/somthing

它将重定向到 bing 站点。

【讨论】:

以上是关于Yarp 反向代理 - 响应 502 错误网关的主要内容,如果未能解决你的问题,请参考以下文章

YARP+AgileConfig 5分钟实现一个支持配置热更新的代理网关

YARP+AgileConfig 5分钟实现一个支持配置热更新的代理网关

微软的反向代理库YARP

微软的反向代理库YARP

将 OIDC 添加到我的 SPA 后反向代理错误网关

.NET反向代理组件YARP的简单使用