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
  1. using System;  
  2. using System.Diagnostics;  
  3. using System.IO;  
  4. using System.Text.RegularExpressions;  
  5. using System.Threading.Tasks;  
  6. namespace Docker.Automation {  
  7.     class Program {  
  8.         static string containerRunCommand = null;  
  9.         static string ip;  
  10.         static void Main(string[] args) {  
  11.             // In this case I am using azurite container, you can use container of your choice  
  12.             Console.WriteLine("Spinning up azurite container...");  
  13.             containerRunCommand = "run --name azurite -p 10000:10000 mcr.microsoft.com/azure-storage/azurite azurite-blob --blobHost 0.0.0.0";  
  14.             RunCommand(containerRunCommand, false);  
  15.             Console.WriteLine("Getting Container IP...");  
  16.             string inspectCommand = string.Concat("inspect -f ""\"{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}\""" azurite");  
  17.             RunCommand(inspectCommand, true);  
  18.             if (ip != null) GetAndSetEnvVariable(ip);  
  19.             Console.WriteLine("Please press any key to exit");  
  20.             Console.ReadLine();  
  21.             Environment.Exit(1);  
  22.         }  
  23.         /// <summary>  
  24.         /// This method runs cmd commands, here in this case will run the container and also inspect the container and get the ipaddress  
  25.         /// </summary>  
  26.         /// <param name="command"></param>  
  27.         /// <param name="stdoutput"></param>  
  28.         private static void RunCommand(string command, bool stdoutput) {  
  29.             var processInfo = new ProcessStartInfo("docker", $ "{command}");  
  30.             processInfo.CreateNoWindow = true;  
  31.             processInfo.UseShellExecute = false;  
  32.             processInfo.RedirectStandardOutput = true;  
  33.             processInfo.RedirectStandardError = true;  
  34.             int exitCode;  
  35.             using(var process = new Process()) {  
  36.                 process.StartInfo = processInfo;  
  37.                 var started = process.Start();  
  38.                 if (stdoutput) {  
  39.                     StreamReader reader = process.StandardOutput;  
  40.                     ip = Regex.Replace(reader.ReadToEnd(), @ "\t|\n|\r""");  
  41.                     if (string.IsNullOrEmpty(ip)) {  
  42.                         Console.WriteLine($ "Unable to get ip of the container");  
  43.                         Environment.Exit(1);  
  44.                     }  
  45.                     Console.WriteLine($ "Azurite conatainer is listening @ {ip}");  
  46.                 }  
  47.                 process.WaitForExit(12000);  
  48.                 if (!process.HasExited) {  
  49.                     process.Kill();  
  50.                 }  
  51.                 exitCode = process.ExitCode;  
  52.                 process.Close();  
  53.                 Console.WriteLine("Azurite is up and running");  
  54.             }  
  55.         }  
  56.         /// <summary>  
  57.         /// This method add/update value for an particular file in a particular folder.  
  58.         /// </summary>  
  59.         /// <param name="ip"></param>  
  60.         public static void GetAndSetEnvVariable(string ip) {  
  61.             try {  
  62.                 // 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.  
  63.                 var path = @ "c:\\DockerDemo\DockerDemoConfig";  
  64.                 var folders = Directory.GetFiles(path, "*.json");  
  65.                 foreach(string fileName in folders) {  
  66.                     if (fileName.Contains("demo", StringComparison.OrdinalIgnoreCase)) {  
  67.                         string configFile = File.ReadAllText(fileName);  
  68.                         dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(configFile);  
  69.                         jsonObj["IpAddress"] = ip;  
  70.                         string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);  
  71.                         File.WriteAllText(fileName, output);  
  72.                         Console.WriteLine("Saved conatiner ip to settings");  
  73.                     }  
  74.                 }  
  75.             } catch (Exception ex) {  
  76.                 // take appropriate action  
  77.             }  
  78.         }  
  79.     }  
  80. }