amazon-web-servicesdocker.net-corekestrelamazon-app-runner

Dockerize .NET 8 Web API Application with Kestrel on AWS App Runner – Port Binding Issue


I'm trying to deploy a .NET 8 Web API application to AWS App Runner using Docker. I've successfully built the Docker image and deployed it, but I'm running into an issue with Kestrel binding to the correct port.

Dockerfile

# Stage 1: Build the application
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
ARG BUILD_CONFIGURATION=Release
WORKDIR /src

COPY ["MainApi.API/MainApi.API.csproj", "MainApi.API/"]
COPY ["MainApi.Application/MainApi.Application.csproj", "MainApi.Application/"]
COPY ["MainApi.Domain/MainApi.Domain.csproj", "MainApi.Domain/"]
COPY ["MainApi.Infrastructure/MainApi.Infrastructure.csproj", "MainApi.Infrastructure/"]
COPY ["MainApi.Persistence/MainApi.Persistence.csproj", "MainApi.Persistence/"]

RUN dotnet restore "MainApi.API/MainApi.API.csproj"

COPY . .

WORKDIR "/src/MainApi.API"
RUN dotnet build "MainApi.API.csproj" -c $BUILD_CONFIGURATION -o /app/build

# Stage 2: Publish the application
FROM build AS publish
RUN dotnet publish "MainApi.API.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false

# Stage 3: Runtime - Final Image
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS final
WORKDIR /app
EXPOSE 80
EXPOSE 443

COPY --from=publish /app/publish .

ENTRYPOINT ["dotnet", "MainApi.API.dll"]

Program.cs (Kestrel Configuration) I’ve configured the Kestrel server in Program.cs to listen on port 80:

var builder = WebApplication.CreateBuilder(args);

// Configure Kestrel to listen on port 80
builder.WebHost.UseUrls("http://0.0.0.0:80");

var app = builder.Build();

// Map default endpoint
app.MapGet("/", () => "Application Started");

// Swagger UI for documentation
app.UseSwagger();
app.UseSwaggerUI();

// Add authentication and authorization middleware
app.UseAuthentication();
app.UseAuthorization();

// Map controllers
app.MapControllers();

// Run the application
app.Run();

Issue I’m encountering the following issues:

When I deploy the application on AWS App Runner, it starts successfully, but the Kestrel server seems not to be binding correctly to the expected port.

AWS App Runner expects the app to run on port 8080, but I’ve explicitly set the app to bind to port 80 in Kestrel.

What I’ve Tried Setting Kestrel to listen on 0.0.0.0:80 via builder.WebHost.UseUrls("http://0.0.0.0:80");

Mapping ports properly using Docker EXPOSE 80 and EXPOSE 443.

I’ve also tried updating the AWS App Runner service settings but the issue persists.

How can I ensure the .NET 8 application listens on the correct port on AWS App Runner with Kestrel? Is there a specific configuration needed?


Solution

  • According to Mehmet Ceylan's 2025-04-28 comment, running docker build --platform linux/amd64 -t apim/mainapi fixes the issue.