title: Get Docker container IP within a .net core application
body: <p>What is the best way to get the current docker container IP address within the container itself using <code>.net core</code>?</p>
  
  <p>I try to register my container to a <code>Consul</code> 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 <code>appsettings.json</code>. I followed this <a href="https://cecilphillip.com/using-consul-for-service-discovery-with-asp-net-core/" rel="noreferrer">tutorial</a>. And when it comes to this section:</p>
  
  <pre><code>// Get server IP address
  var features = app.Properties["server.Features"] as FeatureCollection;
  var addresses = features.Get&lt;IServerAddressesFeature&gt;();
  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" }
  };
  </code></pre>
  
  <p>The received <code>address</code> contains only the loopback address and not the actual container address (as seen from outside - the host where <code>Consul</code> is running). I already tried to use the <code>HttpContext</code> (which is <code>null</code> in the startup class) and the <code>IHttpContextAccessor</code> which also does not contain anything at this time.</p>
  
  <hr>
  
  <p><strong>EDIT</strong>: This is a part of my <code>appsettings.json</code>:</p>
  
  <pre><code>  "ServiceRegistry": {
      "Uri": "http://172.28.112.1:8500",
      "Name": "AuthServiceApi",
      "Id": "auth-service-api-v1",
      "ContainerAddress": "http://&lt;CONTAINER_IP/DNS&gt;",
      "Checks": [
        {
          "Service": "/health",
          "Timeout": 5,
          "Interval":  10 
        }
      ], 
      "Tags": [ "Auth", "User" ]
    }
  </code></pre>
  
  <p>The <code>Uri</code> is the one from my host system and I managed to register the service in Consul. The missing part is the <code>&lt;CONTAINER_IP/DNS&gt;</code> 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).</p>