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条回答
叼着烟拽天下
2楼-- · 2019-01-06 09:26

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
查看更多
男人必须洒脱
3楼-- · 2019-01-06 09:30

Check for all the solutions above in Python:

import os
import subprocess

def in_container():
    # type: () -> bool
    """ Determines if we're running in an lxc/docker container. """
    out = subprocess.check_output('cat /proc/1/sched', shell=True)
    out = out.decode('utf-8').lower()
    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', None) is not None
    ]
    return any(checks)
查看更多
看我几分像从前
4楼-- · 2019-01-06 09:31

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.

查看更多
乱世女痞
5楼-- · 2019-01-06 09:33

Building on the accepted answer that tests /proc/*/cgroup ..

awk -F: '$3 ~ /^\/$/ {c=1} END{ exit c }' /proc/self/cgroup

So for use in a script or so, a test could be constructed this way.

is_running_in_container() {
  awk -F: '$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
查看更多
趁早两清
6楼-- · 2019-01-06 09:35

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
查看更多
一夜七次
7楼-- · 2019-01-06 09:36

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.

查看更多
登录 后发表回答