Deploy ASP.NET Core to Heroku
Goal
Deploy an ASP.NET Core application to Heroku using Docker.
Configure PORT
Heroku sets the PORT environment variable dynamically. Configure your app to use it:
//Program.cs
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
var herokuPort = Environment.GetEnvironmentVariable("PORT");
if (!string.IsNullOrWhiteSpace(herokuPort))
{
webBuilder.UseUrls($"http://*:{herokuPort}");
}
webBuilder.UseStartup<Startup>();
});
Create Dockerfile
FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build-env
WORKDIR /app
## Copy csproj and restore as distinct layers
COPY *.csproj ./
RUN dotnet restore
## Copy everything else and build
COPY . ./
RUN dotnet publish -c Release -o publish
## Build runtime image
FROM mcr.microsoft.com/dotnet/core/aspnet:3.1
WORKDIR /app
COPY --from=build-env /app/publish .
ENTRYPOINT ["dotnet", "Bustroker.Notes.WebUI.dll"]
Deploy via Heroku Container Registry
Create an app in Heroku first, then:
## Install Heroku CLI
curl https://cli-assets.heroku.com/install-ubuntu.sh | sh
## Login
heroku login -i
heroku container:login
## Build and push image
heroku container:push <REPOSITORY_NAME> --app <APP_NAME>
## Deploy container
heroku container:release <REPOSITORY_NAME> --app <APP_NAME>
Access your app at https://<APP_NAME>.herokuapp.com/