Search code examples
asp.net-coredockerfile

Port expose in ASP.NET Core with dockerfile is not working


I've created a default ASP.NET Core 6 project and when I'm creating an image with the command line and trying to expose the port, everything seems to be correct I see the port has been exposed successfully but in the end, I'm not able to open the endpoint.

Does anyone have any idea?

Here are the details - Program.cs

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers();

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

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

app.UseAuthorization();
app.MapControllers();

app.Run();

Here is the dockerfile:

#See https://aka.ms/customizecontainer to learn how to customize your debug container and how Visual Studio uses this Dockerfile to build your images for faster debugging.

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

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

FROM build AS publish
RUN dotnet publish "WebApplication2.csproj" -c Release -o /app/publish /p:UseAppHost=false

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

Then the docker commands are:

docker build -f .\WebApplication2\Dockerfile . -t sample
docker run -p 8080:80 sample

enter image description here

Everything is correct but I get a HTTP 404 error ...


Solution

  • 404 means this web application is working well. You can access one of the api, like https://localhost:44369/weatherforecast, it will show the json data.

    You should move app.UseSwagger(); and app.UseSwaggerUI() out of the condition.

    Sample

    var app = builder.Build();
    
    app.UseSwagger();
    app.UseSwaggerUI();
    
    app.UseAuthorization();
    
    app.MapControllers();
    
    app.Run();