C# 判断当前是否在容器中运行

2020年4月1日 2976点热度 0人点赞 0条评论
内容纲要

可以在容器中执行命令,查看到信息

/egrep  '^1:.+(docker|lxc|kubepods)' /proc/1/cgroup

那么我们可以通过读取文件的方法,去分析是否在容器中运行。

代码如下

            /// <summary>
            /// 是否在容器中运行
            /// </summary>
            /// <returns></returns>
            private static async Task<bool> IsRunAtDocker()
            {
                //egrep  '^1:.+(docker|lxc|kubepods)' /proc/1/cgroup
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    if (!System.IO.File.Exists("/proc/1/cgroup"))
                        return false;
                    try
                    {
                        bool has = false;
                        using (System.IO.StreamReader stream = System.IO.File.OpenText("/proc/1/cgroup"))
                        {
                            while (!stream.EndOfStream)
                            {
                                string s = await stream.ReadLineAsync();
                                string[] ss = s.Split(':');
                                if (s.Contains("name=systemd"))
                                {
                                    if (ss[2].Split('/').Contains("docker"))
                                    {
                                        has = true;
                                        break;
                                    }
                                }
                            }
                        }
                        return has;
                    }
                    catch { return false; }
                }
                else
                {
                    throw new PlatformNotSupportedException($"The current operating system is not supported({nameof(Machine)}).");
                }
            }

痴者工良

高级程序员劝退师

文章评论