How to Work with Docker using C#

How to Work with Docker using C#

In this post, we'll learn about Getting Docker Container IP Address Using C#

Working with Docker is pretty easy, all you need is Docker installed in your machine and a command line tool such as command prompt or powershell to interact with it. You write Docker commands in the tool and docker obeys them. But when asked to do the same using any programming language instead of commands, things starts to look a little weak. Not to worry, in this article I will show you how to work with Docker using C# (the concept will work well with any other object oriented programming language).

Requirement

  1. Spin up a docker container

  2. Get the IP address of the running container

  3. Save the IP address in a specific directory

Solution

using System;  
using System.Diagnostics;  
using System.IO;  
using System.Text.RegularExpressions;  
using System.Threading.Tasks;  
namespace Docker.Automation {  
    class Program {  
        static string containerRunCommand = null;  
        static string ip;  
        static void Main(string[] args) {  
            // In this case I am using azurite container, you can use container of your choice  
            Console.WriteLine("Spinning up azurite container...");  
            containerRunCommand = "run --name azurite -p 10000:10000 mcr.microsoft.com/azure-storage/azurite azurite-blob --blobHost 0.0.0.0";  
            RunCommand(containerRunCommand, false);  
            Console.WriteLine("Getting Container IP...");  
            string inspectCommand = string.Concat("inspect -f ", "\"{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}\"", " azurite");  
            RunCommand(inspectCommand, true);  
            if (ip != null) GetAndSetEnvVariable(ip);  
            Console.WriteLine("Please press any key to exit");  
            Console.ReadLine();  
            Environment.Exit(1);  
        }  
        /// <summary>  
        /// This method runs cmd commands, here in this case will run the container and also inspect the container and get the ipaddress  
        /// </summary>  
        /// <param name="command"></param>  
        /// <param name="stdoutput"></param>  
        private static void RunCommand(string command, bool stdoutput) {  
            var processInfo = new ProcessStartInfo("docker", $ "{command}");  
            processInfo.CreateNoWindow = true;  
            processInfo.UseShellExecute = false;  
            processInfo.RedirectStandardOutput = true;  
            processInfo.RedirectStandardError = true;  
            int exitCode;  
            using(var process = new Process()) {  
                process.StartInfo = processInfo;  
                var started = process.Start();  
                if (stdoutput) {  
                    StreamReader reader = process.StandardOutput;  
                    ip = Regex.Replace(reader.ReadToEnd(), @ "\t|\n|\r", "");  
                    if (string.IsNullOrEmpty(ip)) {  
                        Console.WriteLine($ "Unable to get ip of the container");  
                        Environment.Exit(1);  
                    }  
                    Console.WriteLine($ "Azurite conatainer is listening @ {ip}");  
                }  
                process.WaitForExit(12000);  
                if (!process.HasExited) {  
                    process.Kill();  
                }  
                exitCode = process.ExitCode;  
                process.Close();  
                Console.WriteLine("Azurite is up and running");  
            }  
        }  
        /// <summary>  
        /// This method add/update value for an particular file in a particular folder.  
        /// </summary>  
        /// <param name="ip"></param>  
        public static void GetAndSetEnvVariable(string ip) {  
            try {  
                // can loop through all subfolders and select 1 or more subfolder(s) and then loop through all file lyk below to get the required json file.  
                var path = @ "c:\\DockerDemo\DockerDemoConfig";  
                var folders = Directory.GetFiles(path, "*.json");  
                foreach(string fileName in folders) {  
                    if (fileName.Contains("demo", StringComparison.OrdinalIgnoreCase)) {  
                        string configFile = File.ReadAllText(fileName);  
                        dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(configFile);  
                        jsonObj["IpAddress"] = ip;  
                        string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);  
                        File.WriteAllText(fileName, output);  
                        Console.WriteLine("Saved conatiner ip to settings");  
                    }  
                }  
            } catch (Exception ex) {  
                // take appropriate action  
            }  
        }  
    }  
}  

Thank you for reading!

docker c-sharp ip

What's new in Bootstrap 5 and when Bootstrap 5 release date?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Random Password Generator Online

HTML Color Picker online | HEX Color Picker | RGB Color Picker

C. C++. C#. 차이점 알려드림. 5분 순삭. Explain C.C++.C#. Like I'm Five

C. C++. C#. 차이점 알려드림. 5분 순삭. Explain C.C++.C#. Like I'm Five. 아시죠? C는 C++.C# 줄인말이 아니라는거?

Learn how to perform CRUD operations using C Sharp

QuickStart: CRUD Operations in C Sharp. Learn how to perform CRUD operations using C Sharp for MongoDB databases.

Loops in C++ | For, While, and Do While Loops in C++

In this Video We are going to see how to use Loops in C++. We will see How to use For, While, and Do While Loops in C++.

Using isdigit() in C/C++

In this article, we'll take a look at using the isdigit() function in C/C++. This is a very simple way to check if any value is a digit or not. Let's look

C++ Tutorial for Beginners 19 - C++ Structures | Struct declaration | C++ Data Structures

Welcome to this course on C++ Tutorial for Beginners. In this video we will see How to use C++ Structures.