可以在容器中执行命令,查看到信息
/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)}).");
}
}
标签:容器,判断,false,stream,C#,System,cgroup,proc
From: https://www.cnblogs.com/webenh/p/18216822