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

后端 未结 16 1310
情歌与酒
情歌与酒 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条回答
  • 2020-11-28 18:58

    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. With LXC/Docker containers, it will be something like /lxc/<containerid> or /docker/<containerid> respectively.

    0 讨论(0)
  • 2020-11-28 19:05

    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
    
    0 讨论(0)
  • 2020-11-28 19:06

    My answer only applies for Node.js processes but may be relevant for some visitors who stumble to this question looking for a Node.js specific answer.

    I had the same problem and relying on /proc/self/cgroup I created an npm package for solely this purpose — to detect whether a Node.js process runs inside a Docker container or not.

    The containerized npm module will help you out in Node.js. It is not currently tested in Io.js but may just as well work there too.

    0 讨论(0)
  • 2020-11-28 19:07

    Docker creates a .dockerenv file at the root of the directory tree inside container. You can run this script to verify

    #!/bin/bash
    if [ -f /.dockerenv ]; then
        echo "I'm inside matrix ;(";
    else
        echo "I'm living in real world!";
    fi
    


    MORE: Ubuntu actually has a bash script: /bin/running-in-container and it actually can return the type of container it has been invoked in. Might be helpful. Don't know about other major distros though.

    0 讨论(0)
  • 2020-11-28 19:07

    I have translated JJC's answer into 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
    
    0 讨论(0)
  • 2020-11-28 19:08

    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.

    0 讨论(0)
提交回复
热议问题