Get Docker container IP within a .net core application Get Docker container IP within a .net core application docker docker

Get Docker container IP within a .net core application


Ok, I got it working and it was much easier than I thought.

var name = Dns.GetHostName(); // get container idvar ip = Dns.GetHostEntry(name).AddressList.FirstOrDefault(x => x.AddressFamily == AddressFamily.InterNetwork);

With the container_id/name I could get the IP with an easy compare if it's an IP4 address. I then can use this address and pass it to Consul. The health checks can now successfully call the container with it's IP from the outside host.

I'm still not 100% satisfied with the result because it relies on the "first" valid IP4 address in the AddressList (currently, there are no more so I got this going for me). Any better / more generic solution would still be welcome.


I too had a requirement lyk above where I had to spin up a docker container and get the container IP address and save to some directory all using c#(.net core) (this concept will work with other programming lang as well). Below is the piece of code to achieve that. Please leave a up vote if u like, comment if u didn't.

Note: This method is pretty reliable as it will get the ip-address of the particular container you want.

static void Main(string[] args)        {          Console.WriteLine("Getting Container IP...");          //This command returns back ip address of the required container.          string inspectCommand = string.Concat("inspect -f ", "\"{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}\"", " container ID/Name");          //The command is appended with string 'docker' as all docker commans starts with it          var processInfo = new ProcessStartInfo("docker", $"{inspectCommand}");          processInfo.CreateNoWindow = true;          processInfo.UseShellExecute = false;          processInfo.RedirectStandardOutput = true;          processInfo.RedirectStandardError = true;'          using (var process = new Process())          {            process.StartInfo = processInfo;            var started = process.Start();              StreamReader reader = process.StandardOutput;              //to remove any unwanted char if appended               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}");              Environment.Exit(1);           }}