.net项目中的Docker容器IP地址 [英] Docker container IP address from .net project

查看:117
本文介绍了.net项目中的Docker容器IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个看似简单的任务变得非常困难.

This seemingly simple task turns out very difficult.

我正在尝试从.net项目中获取docker容器的IP,在我的情况下,是使用c#.

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

到目前为止,我已经尝试过(返回的是docker引擎的IP(DockerNAT),而不是容器的IP):

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

如果我使用ipconfig,则该列表不包含容器的IP地址,您可以使用docker network inspect network_name找到它(以下列表不包含容器的IP):

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

还有其他使用C#访问容器IP的想法吗?

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

推荐答案

与大多数人仍需要该IP的人共享答案的答案不同.

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

我同意@ david-maze的观点,在大多数情况下,您甚至不知道IP地址就可以逃脱.使用 docker-compose 创建 yaml 文件后,所有服务都将具有一个友好的名称.

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.

在需要IP地址的情况下,如果要配置一个负载均衡器(我可以想到的一个one脚的用例),应该依靠代码进行配置.

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.

这是一个小用例.

该解决方案包含三个组成部分:

The solution has three components:

  1. docker-compose (具有网络)
  2. .env文件与 docker-compose
  3. 处于同一级别
  4. 在.NET代码中配置环境变量

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 文件

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

这篇关于.net项目中的Docker容器IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆