How to determine if a process runs inside lxc/Dock

2019-01-06 08:53发布

Is there any way to determine if a process (script) runs inside an lxc container (~ Docker runtime)? I know that some programs are able to detect whether they run inside a virtual machine, is something similar available for lxc/docker?

13条回答
▲ chillily
2楼-- · 2019-01-06 09:36

Maybe this do the trick:

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

Is that what you want? Help it help =)

查看更多
Anthone
3楼-- · 2019-01-06 09:37

The easiest way would be to check the environment. If you have the container=lxc variable, you are within a container.

Otherwise, if you are root, you can try to perform mknod or mount operation, if it fails, you are most likely in a container with dropped capabilities.

查看更多
Fickle 薄情
4楼-- · 2019-01-06 09:38

The most reliable way is to check /proc/1/cgroup. It will tell you the control groups of the init process, and when you are not in a container, that will be / for all hierarchies. When you are inside a container, you will see the name of the anchor point; which, with LXC/Docker containers, will be something like /lxc/<containerid> or /docker/<containerid> respectively.

查看更多
来,给爷笑一个
5楼-- · 2019-01-06 09:41

This SO Q&A: "Find out if the OS is running in a virtual environment"; though not the same as the OP's question, it does indeed answer common cases of finding which container you're in (if at all).

In particular, install and read the code of this bash script which seems to work pretty well:

virt-what :

sudo apt install virt-what
查看更多
你好瞎i
6楼-- · 2019-01-06 09:43

Handy Python function to check if running in Docker (linux-only, obvs.):

def in_docker():
    """ Returns: True if running in a Docker container, else False """
    with open('/proc/1/cgroup', 'rt') as ifh:
        return 'docker' in ifh.read()
查看更多
聊天终结者
7楼-- · 2019-01-06 09:45

On a new ubuntu 16.04 system, new systemd & lxc 2.0

sudo grep -qa container=lxc /proc/1/environ
查看更多
登录 后发表回答