Build a Web API Project using .NET 6 in Docker

Michael Oyelami
3 min readMay 2, 2023

--

Source: https://blogit.create.pt/telmorodrigues/2022/03/08/smaller-net-6-docker-images/

This tutorial will gently guide you through how to build a RESTful Web API using .Net 6 and dockerize it.

Required Software

To complete this tutorial, you need the following:

Creating a Web API Project

The first step is to open Visual Studio 2022 and select Create a new project and then select ASP.NET Core Web API:

Create a new project

Click Next and give a name to your project:

Configure your new project

Click Next and select .NET 6.0 as the framework:

Additional information

Click Create.

Add Swagger in release mode

To make it easier to test out the API, we will be adding Swagger in release mode as well. To do this we will move Swagger out of the development environment check in Program.cs file (lines 13 & 14).

Move Swagger out of the development environment

Create a Dockerfile for the application

To build a container image with Docker, a Dockerfile with build instructions is required.

Here’s the complete Dockerfile in the Project folder:

#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.

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

FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /WebAPIProject
COPY ["WebAPIProject/WebAPIProject.csproj", "WebAPIProject/"]
RUN dotnet restore "WebAPIProject/WebAPIProject.csproj"
COPY . .
WORKDIR "/WebAPIProject/WebAPIProject"
RUN dotnet build "WebAPIProject.csproj" -c Release -o /app

FROM build AS publish
RUN dotnet publish "WebAPIProject.csproj" -c Release -o /app

FROM base AS final
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "WebAPIProject.dll"]

Create and run docker-compose for the application

Create file docker-compose.yml in the Solution folder and content of the file is below:

version: '3'

services:

webapi:
image: ${DOCKER_REGISTRY-}webapi
build:
context: .
dockerfile: WebAPIProject/Dockerfile
ports:
- 8080:80

Save All files and Run docker-compose.yml

docker-compose up -d

If everything is correct, docker will build the container and you should see the output in your terminal indicating your container was built and started successfully. Once all the above are done, you can hit the base endpoint http://localhost:8080/swagger to verify it’s working.

Conclusion

In this tutorial, you learnt how to build a RESTful Web API using .Net 6, create a Dockerfile and create a Docker Compose file.

If you’d like to take a look at the code used in our project, Here is git repository for the whole code.

References

--

--

Michael Oyelami

An enthusiastic software developer who builds and maintains both web and mobile applications using C#, TypeScript and Go.