Alex Tyler

Alex Tyler

1586919141

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

What is GEEK

Buddha Community

How to Work with Docker using C#
Iliana  Welch

Iliana Welch

1597368540

Docker Tutorial for Beginners 8 - Build and Run C++ Applications in a Docker Container

Docker is an open platform that allows use package, develop, run, and ship software applications in different environments using containers.
In this course We will learn How to Write Dockerfiles, Working with the Docker Toolbox, How to Work with the Docker Machine, How to Use Docker Compose to fire up multiple containers, How to Work with Docker Kinematic, Push images to Docker Hub, Pull images from a Docker Registery, Push stacks of servers to Docker Hub.
How to install Docker on Mac.

#docker tutorial #c++ #docker container #docker #docker hub #devopstools

Pass method as parameter using C# | Delegates in C# | C# Bangla Tutorial | Advanced C#

https://youtu.be/GfcTSJf5Rc8

#oop in c# #object oriented programming in c# #object oriented concept in c# #learn oop concept #advance c# #pass method as parameter using c#

Ari  Bogisich

Ari Bogisich

1589816580

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 at how to use this function, using some simple examples.

#c programming #c++ #c #c#

Ari  Bogisich

Ari Bogisich

1590565090

A Guide to using the strdup() function in C/C++

In this article, we’ll take a look at using the strdup() function in C/C++.

The strdup() function is very useful if you want to duplicate the contents of a string onto another string.

Let’s see how we can utilize this function, using some simple examples.

#c programming #c++ #c #c#

Iliana  Welch

Iliana Welch

1595249460

Docker Explained: Docker Architecture | Docker Registries

Following the second video about Docker basics, in this video, I explain Docker architecture and explain the different building blocks of the docker engine; docker client, API, Docker Daemon. I also explain what a docker registry is and I finish the video with a demo explaining and illustrating how to use Docker hub

In this video lesson you will learn:

  • What is Docker Host
  • What is Docker Engine
  • Learn about Docker Architecture
  • Learn about Docker client and Docker Daemon
  • Docker Hub and Registries
  • Simple demo to understand using images from registries

#docker #docker hub #docker host #docker engine #docker architecture #api