Containerization of the .NET Core 7 Web API using Docker: A Comprehens

Introduction

In the world of modern software development, containerization has become an essential practice for building, deploying, and managing applications. Docker, one of the most popular containerization platforms, enables developers to package their applications and dependencies into containers that can run consistently across different environments. In this article, we'll explore how to containerize a .NET Core 7 Web API using Docker, providing you with a step-by-step guide and examples to follow along.

Prerequisites

Before we dive into the containerization process, ensure you have the following prerequisites in place:

  1. .NET Core 7: Install the .NET Core SDK 7 on your development machine. You can download it from the official .NET website (https://dotnet.microsoft.com/download).
  2. Docker: Install Docker Desktop or Docker Engine based on your operating system. You can find installation instructions for different platforms on the Docker website (https://docs.docker.com/get-docker/).
  3. .NET Core 7 Web API Project: Create a .NET Core 7 Web API project using your preferred development environment, such as Visual Studio or Visual Studio Code.

Below, I'll provide a step-by-step guide to creating a .NET Core Web API and then containerizing it using Docker. This guide will help you build a Web API and package it into a Docker container.

Step 1. Create a .NET Core Web API Project

Create a New Web API Project: Open your terminal or command prompt and navigate to the directory where you want to create your project. Run the following command.

dotnet new webapi -n MyWebApi

This command creates a new .NET Core Web API project named "MyWebApi."

Step 2. Create a Simple Controller

Create a Controller: In the Controllers folder of your project, you'll find an existing WeatherForecastController.cs. Let's create a new controller.

Create a new file named ValuesController.cs in the Controllers folder and add the following code.

using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;

namespace MyWebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        // GET: api/values
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET: api/values/5
        [HttpGet("{id}")]
        public ActionResult<string> Get(int id)
        {
            if (id == 1)
            {
                return "value1";
            }
            else if (id == 2)
            {
                return "value2";
            }
            else
            {
                return NotFound();
            }
        }
    }
}

This controller defines two basic GET endpoints, similar to the previous example.

Step 3. Configure Routing

Configure Routing: In Startup.cs, ensure that routing is correctly configured. Add the following lines in the ConfigureServices and Configure methods.

// In ConfigureServices method
services.AddControllers();

// In Configure method
app.UseRouting();
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});

Step 4. Build and Run Your API Locally

Run Your API Locally: Open a terminal, navigate to your project directory (cd MyWebApi), and run the following command.

dotnet run

Your API will start, and you'll see a message indicating that the application is listening on a specific URL (e.g., https://localhost:5001).

Step 5. Test Your API

Test Your API: Open a web browser or use a tool like Curl, Postman, or Swagger To test your API.

You should receive JSON responses with the values you defined in the controller.

  • To retrieve all values: GET https://localhost:5001/api/values
  • To retrieve a specific value by ID: GET https://localhost:5001/api/values/1

Step 6. Containerize Your .NET Core Web API using Docker

Now, let's containerize your .NET Core Web API using Docker.

Create a Dockerfile: In your project directory, create a file named Dockerfile (without any file extension) and add the following content.

# Use the official .NET SDK image as a build stage
FROM mcr.microsoft.com/dotnet/sdk:7 AS build

WORKDIR /app

# Copy the project files into the container
COPY . .

# Publish the application
RUN dotnet publish -c Release -o /app/publish

# Use a smaller runtime image for the final stage
FROM mcr.microsoft.com/dotnet/aspnet:7 AS runtime

WORKDIR /app

# Copy the published application from the build stage
COPY --from=build /app/publish .

# Expose port 80 for the application
EXPOSE 80

# Set the entry point for the application
ENTRYPOINT ["dotnet", "MyWebApi.dll"]

Replace MyWebApi.dll with your actual application's DLL name if it's different.

Build the Docker Image: In your terminal, navigate to your project directory (where the Dockerfile is located) and run the following command:

docker build -t mywebapiimage .

This command builds a Docker image tagged as mywebapiimage using the current directory (.) as the build context.

Run the Docker Container: After successfully building the Docker image, run a Docker container from it with the following command:

docker run -d -p 8080:80 --name mywebapicontainer mywebapiimage
  • -d: Runs the container in detached mode.
  • -p 8080:80: Maps port 8080 on your host machine to port 80 in the container.
  • --name mywebapicontainer: Assigns the name mywebapicontainer to the running container.
  • mywebapiimage: Specifies the name of the Docker image to run.

Step 7. Access Your Containerized Web API

Your .NET Core 7 Web API is now running inside a Docker container. To access it, open your web browser or use a tool like curl or Postman and make a request to http://localhost:8080/api/values (or replace /api/values with the appropriate endpoint of your API).

Conclusion

When you need to deploy a .NET Core 7 Web API across different environments, Docker containerization is a powerful way to ensure consistency and reliability. This guide covers the essential steps to create a Dockerfile, build a Docker image, and run a containerized .NET Core Web API. By adhering to these steps and best practices, you can simplify your development and deployment processes, making it easier to manage and scale your applications. I wish you all the best for your coding journey!


Similar Articles