11

What is the best way to get the current docker container IP address within the container itself using .net core?

I try to register my container to a Consul server which is hosted on the Docker host (not as a container) and I need to get the container IP address on startup to make the registration. Because the IP addresses change on any container startup I can't just hard-code it into the appsettings.json. I followed this tutorial. And when it comes to this section:

// Get server IP address
var features = app.Properties["server.Features"] as FeatureCollection;
var addresses = features.Get<IServerAddressesFeature>();
var address = addresses.Addresses.First();

// Register service with consul
var uri = new Uri(address);
var registration = new AgentServiceRegistration()
{
     ID = $"{consulConfig.Value.ServiceID}-{uri.Port}",
     Name = consulConfig.Value.ServiceName,
     Address = $"{uri.Scheme}://{uri.Host}",
     Port = uri.Port,
     Tags = new[] { "Students", "Courses", "School" }
};

The received address contains only the loopback address and not the actual container address (as seen from outside - the host where Consul is running). I already tried to use the HttpContext (which is null in the startup class) and the IHttpContextAccessor which also does not contain anything at this time.


EDIT: This is a part of my appsettings.json:

  "ServiceRegistry": {
    "Uri": "http://172.28.112.1:8500",
    "Name": "AuthServiceApi",
    "Id": "auth-service-api-v1",
    "ContainerAddress": "http://<CONTAINER_IP/DNS>",
    "Checks": [
      {
        "Service": "/health",
        "Timeout": 5,
        "Interval":  10 
      }
    ], 
    "Tags": [ "Auth", "User" ]
  }

The Uri is the one from my host system and I managed to register the service in Consul. The missing part is the <CONTAINER_IP/DNS> which is needed for Consul to perform some checks for that particular container. Here I need either the IP of the container or the DNS on which it is accessible from the host system. I know that this IP will switch with every container starup and it's in the settings only for demonstration purpose (I'm happy if I can get the IP at startup time).

9
  • 2
    May I ask why you not like using docker hostnames? this way you don't have to bother about internal IP addresses at all, as docker acts as DHCP server and (by default) the hostname of a container is it's name. so a containername will get you to one of the containers running in docker
    – Tseng
    Aug 20, 2018 at 7:23
  • Also you should iterate over the addresses.Addresses property. You are just picking the first, there may be other more suitable ones
    – Tseng
    Aug 20, 2018 at 7:24
  • @Tseng: Could I also use it's container_id as hostname because I set container_name in the docker-compose and also use replicas (not sure how this will work together at all)? I'm quite new to docker and was not aware there are such methods. I appreciate other solutions that do not rely on IPs :-)
    – Alex
    Aug 20, 2018 at 7:29
  • This could be useful for you: stackoverflow.com/questions/27670495/…
    – moebius
    Aug 20, 2018 at 9:31
  • Also remember, in a Docker Compose context, Compose will tell Docker each container can be reached under its key in the docker-compose.yml file, which will be different from the container name or the container-private hostname.
    – David Maze
    Aug 20, 2018 at 11:42

2 Answers 2

18

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

var name = Dns.GetHostName(); // get container id
var 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.

8
  • Hi can you post you code? .. where do you set your var ip? do you use it here? var registration = new AgentServiceRegistration() { ID = _registrationID, Name = _consulConfig.Value.ServiceName, Address = $"{uri.Host}", // <-- IP ????? Port = uri.Port, Tags = _consulConfig.Value.Tags.ToArray() }; Jan 17, 2019 at 9:44
  • I ve upvote your anwer cause it give me in the right way .. but plz .. need little bit more help ;) Jan 17, 2019 at 10:05
  • @federicoscamuzzi: I'll answer you tomorrow. Not in town nor access to my repo atm.
    – Alex
    Jan 17, 2019 at 13:39
  • I've DONE IT !!.. now i'm tryng to deploy it on k8 .. REALLY REALLY thnx for your HELP!! Jan 17, 2019 at 13:50
  • 2
    The most reliable way to get a pod IP address is to ask k8s itself. You can add an env var to the container spec and read the value in the app kubernetes.io/docs/tasks/inject-data-application/… Jul 2, 2020 at 13:12
0

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);
           }}
3
  • This gets the container IP from outside the container. The original question asks how to get the container IP from inside the container.
    – x0n
    Sep 14, 2020 at 3:57
  • @x0n If you read the original question it says How to get the running container IP in a .net core application. So my solution does exactly that. Plz read the code properly before giving thums down
    – Priya
    Sep 15, 2020 at 18:19
  • 1
    I did read it -- I think this is a language/context issue. The OP wants to know a container IP from code running inside the same container; this is proven by the answer they accepted (which only works from inside the same container). Your method is calling docker inspect, which will not be available inside the container. I downvoted because your answer does not answer the question.
    – x0n
    Sep 22, 2020 at 16:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.