Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

bash

docker

People also ask

Can you see the processes running inside a container from the outside?

Yes this is normal. LXC containers are not virtualisation of hardware, and so there is a single kernel that is running all of the processes.

Can you run docker inside LXC?

By running docker inside LXC, you get all the gains of running docker in its own isolated environment away from the host, but without the complexities and overhead that would come with running docker in a full VM.


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 can return the type of container it has been invoked in. Might be helpful. Don't know about other major distros though.


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.


On a new ubuntu 16.04 system, new systemd & lxc 2.0

sudo grep -qa container=lxc /proc/1/environ

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

#!/bin/bash
if grep -sq 'docker\|lxc' /proc/1/cgroup; then
   echo I'm running on docker.
fi

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()