How to Work with Docker 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

How to Work with Docker using C#
12.75 GEEK