How to determine if a process runs inside lxc/Docker?

后端 未结 16 1392
情歌与酒
情歌与酒 2020-11-28 18:15

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 v

16条回答
  •  旧时难觅i
    2020-11-28 18:56

    In a docker container, entries /proc/self/cgroup are mounted to cgroups on the host.

    e.g. in a container

    # awk -F: '/cpuset/' /proc/self/cgroup
    3:cpuset:/docker/22bd0c154fb4e0d1b6c748faf1f1a12116acc21ce287618a115ad2bea41256b3
    

    whereas, the same on the host

    $ awk -F: '/cpuset/' /proc/self/cgroup
    3:cpuset:/
    

    Using something in the shell for a low profile test

    is_running_in_container() {
      awk -F: '/cpuset/ && $3 ~ /^\/$/{ c=1 } END { exit c }' /proc/self/cgroup
    }
    
    if is_running_in_container; then
      echo "Aye!! I'm in a container"
    else 
      echo "Nay!! I'm not in a container"
    fi
    

提交回复
热议问题