Docker container IP address from .net project

房东的猫 提交于 2021-01-05 07:41:38

问题


This seemingly simple task turns out very difficult.

I am trying to get docker container's IP from .net project, in my case using c#.

What I have tried so far (This returns docker engine's IP (DockerNAT), not the container's IP):

 Dns.GetHostEntry(name).AddressList.FirstOrDefault(x => x.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);

If I use ipconfig, the list does not contain the container's IP address, which you can find using docker network inspect network_name (Below list doesn't contain container's IP):

 var networkInterfaces = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();

Any other idea to access the container's IP in C#?


回答1:


A different answer than most sharing it anyway for those who need that IP.

I agree with @david-maze that you can get away in most cases without ever knowing the IP address. And with docker-compose creating the yaml file will have a friendly name to all the services.

With that said in events when you just need the IP address, let's say to configure a load balancer (one lame use case that I could think of), you should lean on configuration over code.

Here's a small usecase.

The solution has three components:

  1. docker-compose (with a network)
  2. .env file at the same level as docker-compose
  3. Configuring environment variables in .NET code

1. docker-compose

version: '3.3'
services:
  web_api:
    .
    .
    .
    networks:
      public_net:
        ipv4_address: ${WEB_API_1_IP}
.
.
.
networks:
  public_net:
    driver: bridge
    ipam:
      driver: default
      config:
        - subnet: ${NETWORK_SUBNET}

2. .env file

.
.
.
WEB_API_1_IP=192.168.0.10
WEB_API_2_IP=192.168.0.11
.
.
.
NETWORK_SUBNET=192.168.0.0/24

3. Program.cs AddEnvironmentVariables

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((hostingContext, config) =>
        {
            config.AddEnvironmentVariables();
        })
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });



回答2:


My experience is I pass the Docker Host IP to the Container through Environment Variables. Then the application look up the environment variable value.

As mentioned in a comment above, the docker IP is not useful to look it up. Even for Container on the same host, you can communicate through different port.




回答3:


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# (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.

    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);
           }}


来源:https://stackoverflow.com/questions/53877377/docker-container-ip-address-from-net-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!