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

后端 未结 16 1308
情歌与酒
情歌与酒 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:49

    Check for all the solutions above in 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())
    

    Proof of concept:

    $ docker run --rm -it --mount type=bind,source=${PWD}/incontainer.py,target=/tmp/script.py python:3 python /tmp/script.py
    True
    
    0 讨论(0)
  • 2020-11-28 18:50

    Handy Python function to check if running in Docker:

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

    A concise way to check for docker in a bash script is:

    #!/bin/bash
    if grep docker /proc/1/cgroup -qa; then
       echo I'm running on docker.
    fi
    
    0 讨论(0)
  • 2020-11-28 18:55

    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? Hope it helps =)

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

    Docker is evolving day by day, so we can't say for sure if they are going to keep .dockerenv .dockerinit in the future.

    In most of the Linux flavours init is the first process to start. But in case of containers this is not true.

    #!/bin/bash
    if ps -p1|grep -q init;then  
      echo "non-docker" 
    else 
      echo "docker" 
    fi
    
    0 讨论(0)
提交回复
热议问题