I’m currently looking at ASP.NET webapps and wanted to run one inside a container, rather than directly on my computer. Partly because I like running things in containers, and partly because I don’t currently build webapps on Windows, so want to make sure that any webapps I build/modify will run okay on other platforms.
Prepping Linux
First I’m making sure Ubuntu (Linux) is up to date.
sudo apt update
sudo apt upgrade
Then it’s time to install the DotNet Software Development Kit (SDK) and the ASP.Net Core runtime environment.
sudo apt-get install dotnet-sdk-8.0
sudo apt-get install aspnetcore-runtime-8.0
Creating a Blazor Webapp
With the DotNet SDK installed I can use dotnet commands to create a Blazor webapp.
dotnet new blazor
I could have also used the output option to tell dotnet to create a new app called “geektechstuff” in a new directory:
dotnet new blazor -o geektechstuff
This creates a basic Blazor webapp that demonstrates some functionality, and can be adjusted / edited. I’ve used it as I’m testing DotNet in a container and needed a webapp quickly for testing.
Blazor Container
The default app, which I’ve named ‘dot_net_website’ contains the relevent files needed:
- Program.cs – the entry point for the app
- Components > App.razor – the root app component
- Components > Routes.razor – the router for Blazor
- Components > Pages – a directory to hold the web pages
- dot_net_website.csproj – defining the app project and its dependencies
- Properties > launchsettings.json – defining how the app runs
I then ran the publish command to turn the webapp from a development app to a published webapp.
dotnet publish -c Release -o out
With the webapp ready, I added a Dockerfile to tell Docker how I want to containerise the webapp and how it should run.
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build-env
WORKDIR /App
# Copy everything
COPY . ./
# Restore as distinct layers
RUN dotnet restore
# Build and publish a release
RUN dotnet publish -c Release -o out
# Build runtime image
FROM mcr.microsoft.com/dotnet/aspnet:8.0
WORKDIR /App
COPY --from=build-env /App/out .
EXPOSE 8080
ENTRYPOINT ["dotnet", "dot_net_website.dll"]
The Docker build command then builds the container, in this case I’ve used the -t flag to tag the image as ‘dotnet’:
docker build -t dotnet -f Dockerfile .
The image can then be used to create a running container using the command:
docker run -p 8080:8080 --name dotnettest -d dotnet
With the -p flag mapping my local devices port 8080 to the containers port 8080, with the container called ‘dotnettest’.