有什么方法可以确定一个进程(脚本)是否在lxc容器中运行(~ Docker runtime)?我知道一些程序能够检测它们是否在虚拟机中运行,lxc/docker是否也有类似的功能?


当前回答

也许这样做是有效果的:

if [ -z $(docker ps -q) ]; then
    echo "There is not process currently running"
else
    echo "There are processes running"
fi

这是你想要的吗?希望能有所帮助=)

其他回答

我们使用进程的调度(/proc/$PID/sched)来提取进程的PID。容器内进程的PID与主机上的PID不同(非容器系统)。

例如,容器上的/proc/1/sched的输出 将返回:

root@33044d65037c:~# cat /proc/1/sched | head -n 1
bash (5276, #threads: 1)

在非容器主机上:

$ cat /proc/1/sched  | head -n 1
init (1, #threads: 1)

这有助于区分您是否在容器中。

在bash脚本中检查docker/lxc的一个简单方法是:

#!/bin/bash
if grep -sq 'docker\|lxc' /proc/1/cgroup; then
   echo "I am running on Docker."
fi

在Python中检查以上所有的解决方案:

import os

def in_container():
    proc_1 = r'/proc/1/sched'

    if os.path.exists(proc_1):
        with open(proc_1, 'r') as fp:
            out = fp.read()
    else:
        out = ''

    checks = [
        'docker' in out,
        '/lxc/' in out,
        out.split(' ')[0] not in ('systemd', 'init',),
        os.path.exists('./dockerenv'),
        os.path.exists('/.dockerinit'),
        os.getenv('container') is not None
    ]
    return any(checks)


if __name__ == '__main__':
    print(in_container())

概念证明:

$ docker run --rm -it --mount type=bind,source=${PWD}/incontainer.py,target=/tmp/script.py python:3 python /tmp/script.py
True

有点跑题了,你可以用两种方法检查你是否在容器中:

Cat /proc/1/environ|tr "\0" "\n"|grep容器:如果你在容器中,你会看到容器变量。 Ps -ef | grep '\[':当你在容器中时,你将只看到grep进程,这意味着你看不到内核进程(例如[kthread])。注意:正常的macOS也不显示内核进程。

参考:这个Linux测试页面

这个SO问答:“找出操作系统是否在虚拟环境中运行”;虽然与OP的问题不一样,但它确实回答了找到你所在容器的常见情况(如果有的话)。

特别是,安装并阅读这个bash脚本的代码,它似乎工作得很好:

virt-what:

sudo apt install virt-what