[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
Docker creates
.dockerenv
and(removed in v1.11) files at the top of the container's directory tree so you might want to check if those exist..dockerinit
Something like this should work.
I've created a small python script. Hope someone finds it useful. :-)
We use the proc's sched (/proc/$PID/sched) to extract the PID of the process. The process's PID inside the container will differ then it's PID on the host (a non-container system).
For example, the output of /proc/1/sched on a container will return:
While on a non-container host:
This helps to differentiate if you are in a container or not. eg you can do:
Thomas' solution as code:
Note
The
read
with a dummy variable is a simple idiom for Does this produce any output?. It's a compact method for turning a possibly verbosegrep
orawk
into a test of a pattern.Additional note on read
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:Inside a Docker container some of the control groups will belong to Docker (or LXC):
What works for me is to check for the inode number of the '/.' Inside the docker, its a very high number. Outside the docker, its a very low number like '2'. I reckon this approach would also depend on the FileSystem being used.
Example
Inside the docker:
Outside the docker
In a script: