问题描述
我们开发了两个 ASP.NET CORE (5.0) 微服务并将它们部署在 docker 中 http://localhost:28621/stock http://localhost:62362/user
两者都可以通过浏览器轻松访问。
我们已经将 ocelot 网关用于 API 网关。 当我们在 docker 中部署它时,我们得到了以下错误
warn: Ocelot.DownstreamRouteFinder.Middleware.DownstreamRouteFinderMiddleware[0] requestId: 0HM8658EF6KHC:00000002,prevIoUsRequestId: no prevIoUs request id,message: DownstreamRouteFinderMiddleware setting pipeline errors. IDownstreamRouteFinder returned Error Code: UnabletoFindDownstreamRouteError Message: Failed to match Route configuration for upstream path: /user,verb: GET. warn: Ocelot.Responder.Middleware.ResponderMiddleware[0] requestId: 0HM8658EF6KHC:00000002,message: Error Code: UnabletoFindDownstreamRouteError Message: Failed to match Route configuration for upstream path: /user,verb: GET. errors found in ResponderMiddleware. Setting error response for request path:/user,request method: GET
----------------------------------------- -------------------------------------------------- -----
ocelot.Development.json 如下
{
"Routes": [
{
"DownstreamPathTemplate": "/user","DownstreamScheme": "http","DownstreamHostAndPorts": [
{
"Host": "localhost","Port": 62362
}
],"UpstreamPathTemplate": "/user","UpstreamHttpMethod": [ "Get" ]
},{
"DownstreamPathTemplate": "/stock","Port": 28621
}
],"UpstreamPathTemplate": "/stock","UpstreamHttpMethod": [ "Get" ]
}
],"GlobalConfiguration": {
"BaseUrl": "https://localhost:5021"
}
}
startup.cs
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddOcelot();
}
public async void Configure(IApplicationBuilder app,IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
await app.USEOcelot();
}
}
program.cs
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext,config) =>
{
config.AddJsonFile($"ocelot.
{hostingContext.HostingEnvironment.EnvironmentName}.json",true,true);
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
请指导我们哪里出错了 我们使用的是.net core 5.0
谢谢
解决方法
您的 Ocelot 容器无法使用“DownstreamHostAndPorts”设置访问其他容器的服务:{'Host': 'localhost'}。容器的'localhost'和宿主机的'localhost'不一样!
要解决这个问题,请朝这个方向看:
- 创建 Docker 网络
- 使用 --network-alias 标志在同一网络下运行所有三个容器
- 在 Ocelot json 文件中使用网络别名和默认端口(因为容器可以直接相互通信,所以不需要映射外部端口!)