Create a ASP.NET Core Docker Image

Create a ASP.NET Core Docker Image

This is a simple demo for creating a Docker image for an ASP.NET Core application.

Before starting, ensure you have the following requirements:

  1. Install Docker.

  2. Install the .NET SDK.

  3. Prepare an ASP.NET Core application. You can create a new ASP.NET Core Web API project using the following command:

    1
    $ dotnet new web -n Demo

Create a Dockerfile

Create a Dockerfile in your project directory:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# Use the official ASP.NET runtime image as a base
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
WORKDIR /app

# Use the .NET SDK image to build the application
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /src
COPY ["Demo/Demo.csproj", "Demo/"]
RUN dotnet restore "Demo/Demo.csproj"
COPY . .
WORKDIR "/src/Demo"
RUN dotnet build "Demo.csproj" -c Release -o /app/build

# Publish the application
FROM build AS publish
RUN dotnet publish "Demo.csproj" -c Release -o /app/publish

# Final stage: use the runtime image to run the app
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "Demo.dll"]

Build the Docker Image

Build the Docker image with the following command:

1
$ docker build -t demo-docker -f Dockerfile .

The result will end like:

docker-build-image


List Docker Images

After building the Docker image, you can list all Docker images with:

1
$ docker images

The result will like:

docker-list-images


Run the Container

Using Docker CLI

To run the container in detached mode, use:

1
$ docker run -d -p 8080:80 --name demo-docker demo-docker

Using Docker Compose

  1. Create a docker-compose.yml file. Replace <service_name>, <image_name>, and <container_name> with your actual values.

    Note: Starting from .NET 8, the default port is 8080.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    version: '3'
    services:
    <service_name>:
    image: <image_name>
    container_name: <container_name>
    ports:
    - 5000:8080
    volumes:
    - /home/user/files:/files

    This example mounts the /home/user/files directory on the host to the /files directory inside the container.

    The docker-compose.yml file can also include multiple services, for example:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    version: '3'
    services:
    <service_name1>:
    image: <image_name1>
    container_name: <container_name1>
    ports:
    - 5000:8080
    volumes:
    - /home/user/files:/files

    <service_name2>:
    image: <image_name2>
    container_name: <container_name2>
    ports:
    - 6000:8080
  2. Start the container in detached mode with Docker Compose:

    1
    $ docker-compose up -d
  3. To check the status of your container:

    1
    $ docker ps

References