Multi-stage Dockerization of .NET Application

Multi-stage Dockerization of .NET Application

Multi-stage Docker builds are great for .NET apps because they let you create your app in one stage and put the runtime pieces in a smaller image in the second stage. This makes the Docker image size smaller.

Here's an example of a multi-stage Dockerfile for a .NET application:

# Stage 1: Build the application
FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build
WORKDIR /app

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

# Copy the application source code
COPY . .

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

# Stage 2: Create a smaller runtime image
FROM mcr.microsoft.com/dotnet/core/aspnet:3.1 AS runtime
WORKDIR /app

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

# Expose the port the app runs on
EXPOSE 80

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

Explanation:

  1. Build Stage (build):

    • Uses the .NET SDK image to build the application.

    • Copies the project files, restores dependencies, and then copies the source code.

    • Builds the application using dotnet publish and outputs the artifacts to the out directory.

  2. Runtime Stage (runtime):

    • Uses a smaller .NET runtime image, which doesn't include the build tools.

    • Copies the published artifacts from the build stage (--from=build).

    • Exposes the necessary port (e.g., port 80) that the application listens on.

    • Sets the entry point to run the application using dotnet.

To use this Dockerfile:

  1. Replace YourAppName.dll with the actual name of your application's main executable.

  2. Build the Docker image using the following command:

     docker build -t your-image-name .
    
  3. Run the Docker container:

     docker run -p 8080:80 your-image-name
    

This Dockerfile is for a standard .NET Core application. You might need to make changes depending on your project layout or if you're using a different .NET Core version.

Don't forget to change your-image-name to a good name for your Docker image. This example uses .NET Core 3.1, but you can change the versions in the FROM lines to fit your app's needs.

Did you find this article valuable?

Support LingarajTechhub All About Programming by becoming a sponsor. Any amount is appreciated!