有什么方法可以确定一个进程(脚本)是否在lxc容器中运行(~ Docker runtime)?我知道一些程序能够检测它们是否在虚拟机中运行,lxc/docker是否也有类似的功能?
当前回答
有点跑题了,你可以用两种方法检查你是否在容器中:
Cat /proc/1/environ|tr "\0" "\n"|grep容器:如果你在容器中,你会看到容器变量。 Ps -ef | grep '\[':当你在容器中时,你将只看到grep进程,这意味着你看不到内核进程(例如[kthread])。注意:正常的macOS也不显示内核进程。
参考:这个Linux测试页面
其他回答
也许这样做是有效果的:
if [ -z $(docker ps -q) ]; then
echo "There is not process currently running"
else
echo "There are processes running"
fi
这是你想要的吗?希望能有所帮助=)
golang代码得到pid container_id,你可以得到map container_id get docker image
func GetContainerID(pid int32) string {
cgroupPath := fmt.Sprintf("/proc/%s/cgroup", strconv.Itoa(int(pid)))
return getContainerID(cgroupPath)
}
func GetImage(containerId string) string {
if containerId == "" {
return ""
}
image, ok := containerImage[containerId]
if ok {
return image
} else {
return ""
}
}
func getContainerID(cgroupPath string) string {
containerID := ""
content, err := ioutil.ReadFile(cgroupPath)
if err != nil {
return containerID
}
lines := strings.Split(string(content), "\n")
for _, line := range lines {
field := strings.Split(line, ":")
if len(field) < 3 {
continue
}
cgroup_path := field[2]
if len(cgroup_path) < 64 {
continue
}
// Non-systemd Docker
//5:net_prio,net_cls:/docker/de630f22746b9c06c412858f26ca286c6cdfed086d3b302998aa403d9dcedc42
//3:net_cls:/kubepods/burstable/pod5f399c1a-f9fc-11e8-bf65-246e9659ebfc/9170559b8aadd07d99978d9460cf8d1c71552f3c64fefc7e9906ab3fb7e18f69
pos := strings.LastIndex(cgroup_path, "/")
if pos > 0 {
id_len := len(cgroup_path) - pos - 1
if id_len == 64 {
//p.InDocker = true
// docker id
containerID = cgroup_path[pos+1 : pos+1+64]
// logs.Debug("pid:%v in docker id:%v", pid, id)
return containerID
}
}
// systemd Docker
//5:net_cls:/system.slice/docker-afd862d2ed48ef5dc0ce8f1863e4475894e331098c9a512789233ca9ca06fc62.scope
docker_str := "docker-"
pos = strings.Index(cgroup_path, docker_str)
if pos > 0 {
pos_scope := strings.Index(cgroup_path, ".scope")
id_len := pos_scope - pos - len(docker_str)
if pos_scope > 0 && id_len == 64 {
containerID = cgroup_path[pos+len(docker_str) : pos+len(docker_str)+64]
return containerID
}
}
}
return containerID
}
在新的ubuntu 16.04系统上,新的systemd和lxc 2.0
sudo grep -qa container=lxc /proc/1/environ
在bash脚本中检查docker/lxc的一个简单方法是:
#!/bin/bash
if grep -sq 'docker\|lxc' /proc/1/cgroup; then
echo "I am running on Docker."
fi
我已经将JJC的答案翻译成ruby
def in_docker
File.open('/proc/1/cgroup', 'rt') do |f|
contents = f.read
return contents =~ /docker/i || contents =~ /kubepod/i
end
rescue StandardError => e
p 'Local development'
p e
false
end
推荐文章
- 为什么用反斜杠开始shell命令?
- 如何找到Java堆大小和内存使用(Linux)?
- 在Bash Shell脚本中生成1到10之间的随机数
- 遍历带空格的文件列表
- 如何在bash中使用mod操作符?
- 在Bash中检查传递的参数是否为文件或目录
- Bash:无限睡眠(无限阻塞)
- 递归复制文件夹,不包括一些文件夹
- 在Bash中传递带有空格的字符串作为函数参数
- 如何使Python脚本在Linux中像服务或守护进程一样运行
- 如何在文件中grep不区分大小写的字符串?
- 如何使用文件的行作为命令的参数?
- time_t最终的类型定义是什么?
- 如何从DockerFile运行docker实例?
- 我是否试图连接到启用TLS的没有TLS的守护进程?