Dotnet - Publish in Docker Container

Overview

For ease of testing, I need to publish my service inside a Docker container. The aim is to :

  • Get the smallest docker image possible
  • See the behaviour of the service on startup and shutdown
  • Expose service API and test them.

The fast way

Using .Net Core 8.0, there is now a built in way to perform such task. It doesn’t require the use of any docker related file, everything is done when building the service :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <InvariantGlobalization>true</InvariantGlobalization>
    <PublishAot>false</PublishAot>
    <UserSecretsId>dotnet-FhaSvc-fd875872-55c2-4789-af4a-2ac5b75d9a99</UserSecretsId>
    <DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
    <ContainerRepository>demo.fha.generic.svc</ContainerRepository>
  </PropertyGroup>

Building the package :

dotnet publish --os linux --arch x64 -p:PublishProfile=DefaultContainer -c Release 

Build result in Terminal In my local Docker, I can see the package : Image in docker

By adding a ContainerFamily we can trim down the image :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <InvariantGlobalization>true</InvariantGlobalization>
    <PublishAot>false</PublishAot>
    <UserSecretsId>dotnet-FhaSvc-fd875872-55c2-4789-af4a-2ac5b75d9a99</UserSecretsId>
    <DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
    <ContainerRepository>riva.fha.generic.svc</ContainerRepository>
    <ContainerFamily>jammy-chiseled</ContainerFamily>
  </PropertyGroup>

The image size has been updated : Image in Docker with smaller size

Tags can be added to the image :

1
    <ContainerImageTags>0.0.1;latest</ContainerImageTags>

Both versions can be viewed in Docker : Image in Docker with smaller size

References