Run And Test ASP.NET Core Web API Docker Container

Introduction
This article describes how to run and test ASP.NET Core Web API Docker container using Docker Desktop.
Topics covered
This article demonstrates how to build the following:
Create a simple ASP.NET Core Web API
Create a Docker image using Visual Studio
Build and run Docker container locally
Pre-requisites
Download and install Visual Studio 2019.
Download and install Postman.
Download and install Docker Desktop.
Tools
Visual Studio 2019
Docker
Postman
Related Resources
Task 1 - Create a simple ASP.NET Core Web API
In this task, you will see how to create a new simple ASP.NET Core Web API using Visual Studio 2019.
Step 1
Open Visual Studio 2019, click Create a new project.

Step 2
Search ASP.NET in the search bar, select ASP.NET Core Web API project template and click Next.
Step 3
Enter the project name as DemoCoreWebAPI. Click Next.

Step 4
Select .NET 5.0 (Current) as Target Framework. Click Create.

Step 5
Expand Controller folder in the solution explorer, right click WeatherForecastController.cs file and click Delete. Right click WeatherForecast.cs file and click Delete.

Step 6
Right click Controllers folder, click Add and then click Controller.
Step 7
Select API-> API Controller with read/write actions. Click Add.
Step 8
Leave the default name and click Add.
Step 9
Hit F5 to run the API locally and Swagger will be displayed. Try out the default endpoints.
Task 2 - Create a Docker image using Visual Studio
In this task, you will see how to create a Docker image for ASP.NET Core Web API using Visual Studio 2019.
Step 1
In the solution explorer, right click on the project, click Add->Docker Support.
Step 2
Select Linux as Target OS. Docker file is created as shown below.
Task 3 - Build and Run Docker container Locally
In this task, you will see how to build and run Docker image inside container locally using Docker Desktop. Note: I am using Windows machine.
Step 1
Open command prompt.
Step 2
Navigate to solution folder. Make sure Docker file is available in solution folder location or else copy the generated Docker file and place it in the location where the solution file is available.
Step 3
Execute the below command to create the Docker image.
docker build -t aspnetcorewebapiimage -f Dockerfile .
Step 4
Execute the below command to view all the Docker images.
docker images
Step 5
Execute the below command to create and run a container.
docker run -d -p 8080:80 --name aspnetcorewebapicontainer aspnetcorewebapiimage
Step 6
Open Docker desktop, click Containers/Apps. You can see a new container named aspnetcorewebapicontainer running as shown below.
Step 7
Open browser and enter the following URL to get the results.
http://localhost:8080/api/values
Summary
This article describes how to run and test ASP.NET Core Web API Docker container using Docker Desktop.

Post a Comment

0 Comments