11 Dec 2020 ~ 2 min read

Building Blazor WebAssembly project with Docker in .NET 5


Blazor is a new ASP.NET framework feature which lets you build interactive web applications. Currently there isn't any Visual Studio IDE option for Docker and WebAssembly only hosted projects. But we can get around this by creating our own Dockerfile to build the project and serve the static files using nginx.

If you're using the Docker compose integration through Visual Studio, you will encounter an error dialog when running the project (it still works!) because it's not a .NET runtime executable (remember we're just serving static files). Alternatively, if you don't want annoying error messages every time you run, separate this application from your backend services and run it outside of the Visual Studio controlled Docker compose configuration.

Dockerfile

FROM mcr.microsoft.com/dotnet/sdk:5.0-buster-slim AS build-env
WORKDIR /TooBigToFailBurgerShopWebSPA

COPY /web/TooBigToFailBurgerShopWebSPA/ .
RUN dotnet restore "TooBigToFailBurgerShopWebSPA.csproj"
RUN dotnet build "TooBigToFailBurgerShopWebSPA.csproj" -c Release -o /build

FROM build-env AS publish
RUN dotnet publish "TooBigToFailBurgerShopWebSPA.csproj" -c Release -o /publish

FROM nginx:alpine AS final
WORKDIR /usr/share/nginx/html

COPY --from=publish /publish/wwwroot /usr/local/webapp/nginx/html
COPY web/TooBigToFailBurgerShopWebSPA/nginx.conf /etc/nginx/nginx.conf

Simple nginx configuration

events { }
http {
    include mime.types;
    types {
        application/wasm wasm;
    }

    server {
        listen 80;

        location / {
            root /usr/local/webapp/nginx/html;
            try_files $uri $uri/ /index.html =404;
        }
    }
}

Build

 docker build -t blazingburgers .

Run

docker run -p 8080:80 blazingburgers

Once the container is running, visit the following URL in your browser and you should see your application.

Go to http://localhost:8080/

Headshot of Jason Watson

Hi, I'm Jason. I'm a software engineer and architect. You can follow me on Twitter, see some of my work on GitHub, or read more about me on my website.