在docker容器内 获取swarm节点IP

想在应用内获取当前swarm节点的IP
使用.net 6框架 vs2022开发工具

步骤一 在镜像中安装docker-ce-cli

修改Dockerfile,在原FROM mcr.microsoft.com/dotnet/runtime:6.0 AS base 和WORKDIR /app之间添加

FROM mcr.microsoft.com/dotnet/runtime:6.0 AS base
### 开始添加内容
WORKDIR /src
RUN sed -i 's/deb.debian.org/mirrors.ustc.edu.cn/g' /etc/apt/sources.list  ; \
    apt-get  -y   -q update ; \    
### BEGIN docker for CI tests
    apt-get install -y --no-install-recommends  ca-certificates curl gnupg ; \
    install -m 0755 -d /etc/apt/keyrings ; \
    curl -fsSL https://download.docker.com/linux/debian/gpg | gpg --dearmor -o /etc/apt/keyrings/docker.gpg ; \
    echo \
         "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://mirrors.tuna.tsinghua.edu.cn/docker-ce/linux/debian \
         "$(. /etc/os-release && echo "$VERSION_CODENAME")" stable" | tee /etc/apt/sources.list.d/docker.list > /dev/null ; \    
    apt-get update ; \
    apt-get install -y --no-install-recommends docker-ce-cli ; \
    apt remove -y curl gnupg  ; \
    apt clean ; \
    apt autoremove -y ; \
    apt -f install ; 
### END docker for CI tests
### 结束添加
WORKDIR /app

步骤二 挂载 /var/run/docker.sock文件

/var/run/docker.sock简单地说,它是Docker守护进程(Docker daemon)默认监听的Unix域套接字(Unix domain socket),容器中的进程可以通过它与Docker守护进程进行通信。
在docker-compose.yml中挂载

volumes:
      - /var/run/docker.sock:/var/run/docker.sock

获取IP的代码

简单测试代码

try
{
    string fileName = "docker";
    string arguments = "info  -f '{{.Swarm.NodeAddr}}'";
    var psi = new ProcessStartInfo(fileName, arguments) { RedirectStandardOutput = true };
    var process = Process.Start(psi);
    if (process == null)
    {
        Console.WriteLine("查询docker info的Process为null。");

    }
    else
    {
        // *** Read the streams ***
       var outputStream = process.StandardOutput.ReadToEnd();
        Console.WriteLine("IP:" + outputStream.Replace("'", ""));
        process.Close();
    }
}
catch (Exception e)
{
    Console.WriteLine(e.ToString());
}

你可能感兴趣的:(docker,容器,.net,6)