. NET 5.0 web项目-无法在启动时更改连接URL (+ Docker)



我想我几乎尝试了所有可能的方法,但无论我做什么,我的。NET 5.0 web应用程序总是连接到localhost:5000

在启动时,我得到这个:

webbackend     | warn: Microsoft.AspNetCore.Server.Kestrel[0]
webbackend     |       Unable to bind to http://localhost:5000 on the IPv6 loopback interface: 'Cannot assign requested address'.
webbackend     | info: Microsoft.Hosting.Lifetime[0]
webbackend     |       Now listening on: http://localhost:5000
webbackend     | info: Microsoft.Hosting.Lifetime[0]
webbackend     |       Application started. Press Ctrl+C to shut down.
webbackend     | info: Microsoft.Hosting.Lifetime[0]
webbackend     |       Hosting environment: Production
webbackend     | info: Microsoft.Hosting.Lifetime[0]
webbackend     |       Content root path: /app

尽管我有这些:

Program.cs:

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.AddConsole();
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseKestrel()
.UseStartup<Startup>()
.UseUrls(http://0.0.0.0:80);
});

appsettings.json:

"commands": {
"web": "Microsoft.AspNet.Server.Kestrel --server.urls http://0.0.0.0:80"
}

Dockerfile:

ENTRYPOINT ["dotnet", "webbackend.dll", "--urls", "http://0.0.0.0:80"]

docker-compose.yml:

webbackend:
image: local_webbackend
container_name: webbackend
networks:
- my_network
environment:
ASPNETCORE_URLS: http://+:80
ports:
- "5001:80"
expose:
- "5432"
- "5001"
depends_on:
postgresdb:
condition: service_healthy

我真的不明白这是怎么回事。

我只是想这个应用程序连接到localhost:80内的docker容器。这个端口应该连接到docker-compose网络中的5001

首先你可以在Program.cs IHostBuilder中更改userls设置

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.AddConsole();
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseKestrel()
.UseStartup<Startup>()
.UseUrls("http://localhost:80/");
});

您可以使用Visual Studio创建的默认Dockerfile或从Microsoft docs下载它(您也可以在docker-compose中指定所有参数,重要的是要公开端口80,或您在上述设置中指定的其他端口)。默认情况下,设置暴露端口80。在你的docker-compose文件中,你可以这样设置:

webbackend:
image: local_webbackend
build: <path to generated or created Dockerfile>
container_name: webbackend
networks:
- my_network
environment:
ASPNETCORE_URLS: http://+:80
ports:
- "5001:80"
depends_on:
postgresdb:
condition: service_healthy

通过这个设置,docker网络中的应用应该使用URL: webback:80来连接到你的应用。您可以从PC上使用:localhost:5001和LAN上的其他设备::5001(例如192.168.1.100:5001)访问该应用程序。

最新更新