Dockerizing .NET Core Applications

A comprehensive guide to deploying your .NET Core applications with Docker.

Dockerizing .NET Core Applications

This tutorial will guide you through the process of containerizing your .NET Core applications using Docker. Docker is a powerful platform for building, shipping, and running applications in containers, which are isolated environments that package application code with its dependencies.

Why Dockerize .NET Core?

Prerequisites

Before you begin, ensure you have the following installed:

Step 1: Create a Sample .NET Core Application

If you don't have an application ready, you can create a simple web API. Open your terminal or command prompt and run:

dotnet new webapi -o MyDockerApp
cd MyDockerApp

Step 2: Create a Dockerfile

In the root directory of your project (MyDockerApp), create a file named Dockerfile (no extension) with the following content:

# Use the official .NET SDK as a parent image
            FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build AS dotnet6
            WORKDIR /app

            # Copy the C# project and restore dependencies
            COPY *.csproj ./
            RUN dotnet restore

            # Copy the rest of the application
            COPY . .

            # Build the application
            RUN dotnet publish -c Release -o out

            # Use a smaller base image for the runtime
            FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS runtime
            WORKDIR /app
            COPY --from=dotnet6 /app/out .

            # Expose the port the application runs on
            EXPOSE 80

            # Define the entrypoint
            ENTRYPOINT ["dotnet", "MyDockerApp.dll"]
Note: This Dockerfile uses a multi-stage build. The first stage builds the application, and the second stage creates a smaller image with only the necessary runtime components, reducing the final image size. Adjust the SDK and ASP.NET Core versions (e.g., 6.0) to match your .NET Core version.

Step 3: Build the Docker Image

Navigate to your project directory in the terminal and build the Docker image:

docker build -t my-dotnet-app .

This command tags your image with the name my-dotnet-app.

Step 4: Run the Docker Container

Now, run your Docker image as a container:

docker run -p 8080:80 my-dotnet-app

This command maps port 8080 on your host machine to port 80 inside the container. Your .NET Core application should now be accessible at http://localhost:8080.

Step 5: Verify the Application

Open your web browser and navigate to http://localhost:8080. You should see the output of your web API. If you created a default web API, you might be able to access the Swagger UI at http://localhost:8080/swagger.

Further Considerations

Congratulations! You have successfully containerized your .NET Core application using Docker. This is a fundamental step towards building robust, scalable, and portable applications.