Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a process is running inside docker container?

[Updated1] I have a shell which will change TCP kernel parameters in some functions, but now I need to make this shell run in Docker container, that means, the shell need to know it is running inside a container and stop configuring the kernel.

Now I'm not sure how to achieve that, here is the contents of /proc/self/cgroup inside the container:

9:hugetlb:/ 8:perf_event:/ 7:blkio:/ 6:freezer:/ 5:devices:/ 4:memory:/ 3:cpuacct:/ 2:cpu:/docker/25ef774c390558ad8c4e9a8590b6a1956231aae404d6a7aba4dde320ff569b8b 1:cpuset:/ 

Any flags above can I use to figure out if this process is running inside a container?

[Updated2]: I have also noticed Determining if a process runs inside lxc/Docker, but it seems not working in this case, the content in /proc/1/cgroup of my container is:

8:perf_event:/ 7:blkio:/ 6:freezer:/ 5:devices:/ 4:memory:/ 3:cpuacct:/ 2:cpu:/docker/25ef774c390558ad8c4e9a8590b6a1956231aae404d6a7aba4dde320ff569b8b 1:cpuset:/ 

No /lxc/containerid

like image 287
harryz Avatar asked May 07 '14 08:05

harryz


People also ask

How do I know if an application is running in a container?

You can also use docker top <name of your container> to check process running in your container.

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.


2 Answers

Docker creates .dockerenv and .dockerinit (removed in v1.11) files at the top of the container's directory tree so you might want to check if those exist.

Something like this should work.

#!/bin/bash if [ -f /.dockerenv ]; then     echo "I'm inside matrix ;("; else     echo "I'm living in real world!"; fi 
like image 124
at0S Avatar answered Sep 18 '22 09:09

at0S


To check inside a Docker container if you are inside a Docker container or not can be done via /proc/1/cgroup. As this post suggests you can to the following:

Outside a docker container all entries in /proc/1/cgroup end on / as you can see here:

vagrant@ubuntu-13:~$ cat /proc/1/cgroup 11:name=systemd:/ 10:hugetlb:/ 9:perf_event:/ 8:blkio:/ 7:freezer:/ 6:devices:/ 5:memory:/ 4:cpuacct:/ 3:cpu:/ 2:cpuset:/ 

Inside a Docker container some of the control groups will belong to Docker (or LXC):

vagrant@ubuntu-13:~$ docker run busybox cat /proc/1/cgroup 11:name=systemd:/ 10:hugetlb:/ 9:perf_event:/ 8:blkio:/ 7:freezer:/ 6:devices:/docker/3601745b3bd54d9780436faa5f0e4f72bb46231663bb99a6bb892764917832c2 5:memory:/ 4:cpuacct:/ 3:cpu:/docker/3601745b3bd54d9780436faa5f0e4f72bb46231663bb99a6bb892764917832c2 2:cpuset:/ 
like image 40
Thomas Uhrig Avatar answered Sep 19 '22 09:09

Thomas Uhrig