Home > OS >  Application Error on Heroku with Docker and Asp.net core
Application Error on Heroku with Docker and Asp.net core

Time:02-26

I am hosting an asp.net core api on Heroku using Docker and github actions.

When the actions runs, everything is fine and the app is deployed. After I go to the url, I have an Application Error message. Here is the concerned part in my logs

2022-02-17T16:41:54.949789 00:00 app[web.1]: [16:41:54 DBG] Failed to bind to http://[::]:80 (IPv6Any). Attempting to bind to http://0.0.0.0:80 instead.
2022-02-17T16:41:54.966069 00:00 app[web.1]: Unhandled exception. System.Net.Sockets.SocketException (13): Permission denied

After some searchs, I have found this post, this previous question and also this one saying to set the port in the Program.cs file or to set ASPNETCORE_URLS=http://*:$PORT in the Dockerfile. I have tried both but nothing worked. Here is my Dockerfile

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

FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY ["PeerNotation.Api.csproj", "."]
RUN dotnet restore "PeerNotation.Api.csproj"
COPY . .
WORKDIR "/src"
RUN dotnet build "PeerNotation.Api.csproj" -c Release -o /app/build
FROM build AS publish
RUN dotnet publish "PeerNotation.Api.csproj" -c Release -o /app/publish
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "PeerNotation.Api.dll"]

and the code snippet from my Program.cs file

var port = Environment.GetEnvironmentVariable("PORT");
builder.WebHost.UseUrls($"http://*:{port}");

(I have tried to log the port and it is never null)

CodePudding user response:

After some researchs, i have found that I was setting the port using the wrong way. I should add the url to the WebApplication object like this :

if (app.Environment.IsProduction())
{
    var port = Environment.GetEnvironmentVariable("PORT");
    app.Urls.Add($"http://*:{port}");
}

And now, the app uses the correct port.

CodePudding user response:

I had the same problem. As mentioned here asp net core 6.0 kestrel server is not working, .NET 6 does not use UseUrls() anymore.

Following the guide from the mentioned link I added this snippet to my Program.cs:

var portExists = int.TryParse(Environment.GetEnvironmentVariable("PORT"), out var port);
if (portExists)
{
    builder.WebHost.ConfigureKestrel(options =>
    {
        options.ListenAnyIP(port);
    });
}

After deployment application started working without errors in Heroku.

  • Related