swagger Docker运行命令类似于Visual Studio中的命令

tjjdgumg  于 2022-11-06  发布在  Docker
关注(0)|答案(2)|浏览(223)

当运行由Visual Studio 2022创建的标准ASP.NET Core Web API项目并启用Docker选项时,可以使用https://localhost:65215/swagger/index.html(甚至会自动弹出)通过浏览器连接到服务器。
当运行容器并指定端口80和443的Map(例如65214和65215)时,在指定的端口上不可能到达Swagger。因此,很明显,它必须有更多的内容。
如何使用docker run命令从控制台运行docker容器?如何设置或至少标识端口?

停靠文件

FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY ["WebApiContainerized/WebApiContainerized.csproj", "WebApiContainerized/"]
RUN dotnet restore "WebApiContainerized/WebApiContainerized.csproj"
COPY . .
WORKDIR "/src/WebApiContainerized"
RUN dotnet build "WebApiContainerized.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "WebApiContainerized.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "WebApiContainerized.dll"]

程序.cs

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) {
    app.UseSwagger();
    app.UseSwaggerUI(); }

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

项目创建

5sxhfpxr

5sxhfpxr1#

假设您的代码包含类似于以下内容的内容...

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
}

... Swagger仅在由ASPNETCORE_ENVIRONMENT环境变量控制的开发环境模式下可用。
最简单的方法是将其设置为***Development***,作为run命令的一部分:

docker run -p 65215:80 -e ASPNETCORE_ENVIRONMENT=Development yourimage:yourtag
yqhsw0fo

yqhsw0fo2#

默认情况下,Swagger仅在您在“开发”环境中运行应用时可用。
默认情况下,容器化的应用程序在生产环境中运行。
要更改它,您可以将ASPNETCORE_ENVIRONMENT变量设置为'Development'。您可以在docker run上执行此操作,也可以在Docker文件中设置它。
至于端口,微软在aspnet映像中将ASPNETCORE_URLS设置为http://+:80,导致应用程序侦听端口80。
添加一行以将ASPNETCORE_ENVIRONMENT设置到您的Dockerfile,如下所示

FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
WORKDIR /app
ENV ASPNETCORE_ENVIRONMENT Development
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY ["WebApiContainerized/WebApiContainerized.csproj", "WebApiContainerized/"]
RUN dotnet restore "WebApiContainerized/WebApiContainerized.csproj"
COPY . .
WORKDIR "/src/WebApiContainerized"
RUN dotnet build "WebApiContainerized.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "WebApiContainerized.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "WebApiContainerized.dll"]

构建和运行

docker build -t myimage .
docker run -d -p 65214:80 myimage

现在,您应该可以访问Swagger页面,网址为http://localhost:65214/swagger

相关问题