How to determine if a process runs inside lxc/Docker?
Solution 1:
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.
Solution 2:
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.
Solution 3:
On a new ubuntu 16.04 system, new systemd & lxc 2.0
sudo grep -qa container=lxc /proc/1/environ
Solution 4:
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