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

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

提交回复
热议问题