paint-brush
How to Run a Microsoft .NET Docker Image in C#by@ssukhpinder
223 reads

How to Run a Microsoft .NET Docker Image in C#

by Sukhpinder SinghFebruary 22nd, 2023
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Docker is an efficient and portable way to package and distribute applications. Microsoft .NET developers can take advantage of Docker to simplify their development workflow. This article will explore how to run a Microsoft.NET Docker image from code in C#. You will need to have the following software installed on your machine: Docker Desktop, Visual Studio or the Docker Core SDK.
featured image - How to Run a Microsoft .NET Docker Image in C#
Sukhpinder Singh HackerNoon profile picture

Docker has become an essential tool in modern software development, providing an efficient and portable way to package and distribute applications.


Microsoft .NET developers can take advantage of Docker to simplify their development workflow and improve the consistency and reliability of their applications. This article will explore how to run a Microsoft .NET Docker image from code in C#.

Prerequisites

Before getting started, you will need to have the following software installed on your machine:


  • Docker Desktop


  • Visual Studio or .NET Core SDK


You will also need a basic understanding of Docker concepts, such as images and containers.

Getting Started

We will create a new C# console application in Visual Studio. Open Visual Studio and select File > New > Project. Choose Console App (.NET Core) as the project type, and give it a name such as DockerCSharp.


Next, open the Program.cs file and replace the existing code with the following:

using Docker.DotNet;
using Docker.DotNet.Models;
using System;
using System.IO;
using System.Threading.Tasks;

namespace DockerCSharp
{
    class Program
    {
        static async Task Main(string[] args)
        {
            // Define Docker API client configuration
            var dockerConfig = new DockerClientConfiguration(new Uri("npipe://./pipe/docker_engine"));

            // Create Docker API client
            var dockerClient = dockerConfig.CreateClient();

            // Define container configuration
            var containerConfig = new Config()
            {
                Image = "mcr.microsoft.com/dotnet/sdk:5.0",
                Cmd = new[] { "dotnet", "new", "console", "-o", "/app", "--no-https" },
                HostConfig = new HostConfig()
                {
                    AutoRemove = true,
                    Binds = new[] { $"{Directory.GetCurrentDirectory()}/app:/app" }
                }
            };

            // Create container
            var containerCreateResponse = await dockerClient.Containers.CreateContainerAsync(containerConfig);
            var containerId = containerCreateResponse.ID;

            // Start container
            await dockerClient.Containers.StartContainerAsync(containerId, new ContainerStartParameters());

            // Wait for container to finish executing
            var containerWaitResponse = await dockerClient.Containers.WaitContainerAsync(containerId);

            // Inspect container logs
            var containerLogsStream = await dockerClient.Containers.GetContainerLogsAsync(containerId, new ContainerLogsParameters()
            {
                ShowStdout = true,
                ShowStderr = true,
                Follow = false
            });
            using (var containerLogsReader = new StreamReader(containerLogsStream))
            {
                Console.WriteLine(containerLogsReader.ReadToEnd());
            }

            // Remove container
            await dockerClient.Containers.RemoveContainerAsync(containerId, new ContainerRemoveParameters());
        }
    }
}


This code defines a C# console application that uses Docker.DotNet NuGet package to interact with the Docker API. The application does the following:


  1. Illustrates the Docker API client configuration and creates a Docker API client instance.


  2. Defines the container configuration, which specifies the Microsoft .NET Docker image to use, the command to run inside the container (dotnet new console), the output directory, and a bind mount to the local app directory.


  3. Creates a container using the container configuration.


  4. Starts the container.


  5. Waits for the container to finish executing.


  6. Inspects the container logs and writes them to the console.


  7. Removes the container.


Note that the code assumes that the Docker API is available at the default named pipe endpoint on Windows, npipe://./pipe/docker_engine.


Now, let's run the container and see if everything is working as expected. We'll use the Docker SDK for .NET to interact with the Docker engine and create a container based on the microsoft/dotnet image we just pulled.


Here's an example of how to do it:

using Docker.DotNet;
using Docker.DotNet.Models;

public async Task RunContainer()
{
    var endpoint = "npipe://./pipe/docker_engine"; // This is the default endpoint for Docker on Windows
    
    var dockerClient = new DockerClientConfiguration(new Uri(endpoint)).CreateClient();
    
    var containerConfig = new Config()
    {
        Image = "microsoft/dotnet",
        Cmd = new List<string>() { "run", "ConsoleApp.dll" } // Replace with the name of your application's entry point
    };
    
    var containerHostConfig = new HostConfig()
    {
        PortBindings = new Dictionary<string, IList<PortBinding>>()
        {
            { "5000/tcp", new List<PortBinding>(){ new PortBinding { HostPort = "5000" } } }
        }
    };
    
    var container = await dockerClient.Containers.CreateContainerAsync(new CreateContainerParameters(containerConfig)
    {
        HostConfig = containerHostConfig,
        Name = "my-dotnet-app"
    });
    
    await dockerClient.Containers.StartContainerAsync(container.ID, new ContainerStartParameters());
}


The code does the following:

  1. Creates a new instance of the DockerClient class, which represents a connection to the Docker engine.


  2. Defines the configuration for the container by specifying the microsoft/dotnet image and the command to run our application. In this case, we're running. ConsoleApp.dll.


  3. Specifies the host configuration, which includes port bindings. We're binding port 5000 in the container to port 5000 on the host machine.


  4. Creates the container using the configuration we just defined.


  5. Starts the container.


You can navigate your web browser to see if everything is working. If everything is working correctly, you should see your application's output in the browser.

Conclusion

This article shows you how to run a Microsoft .NET Docker image from code using the Docker SDK for .NET. With this technique, you can easily package and deploy your .NET applications as Docker containers, making managing and deploying dependencies to different environments easier.

Follow Me On

C# Publication, LinkedIn, Instagram, Twitter, Dev.to, BuyMeACoffee


Also published here