How to check if a process is running from within a Docker container? I'd like a method that works reliably, and that is future-proof.
This was already asked and answered at How to determine if a process runs inside lxc/Docker?, however the answer is quite old, and it does not seem to work on a recent setup (Linux host with cgroups v2 enabled, Docker 20.10.x, kernel 5.10.x).
The top-rated answer (from the link above) suggests to check for the string docker
in /proc/1/cgroup
, however here's what I get:
# cat /proc/1/cgroup
0::/
It seems to be due to the fact that cgroups v2 is enabled on my host (it used to work with cgroups v1).
Another answer suggests to check for the existence of the file /.dockerenv
. It works:
# test -e /.dockerenv && echo ok
ok
However a comment from a Docker's maintainer (dated from 2016) suggests NOT to rely on this file (emphasis mine):
Originally, ".dockerenv" was for transmitting the environment variables of the container across the container boundary -- I would not recommend relying on its existence either (IIRC, that code you've linked to is the only reason it still exists). There's likely something incriminatory inside /sys/fs/cgroup, but I haven't checked recently.
-- https://github.com/moby/moby/issues/18355#issuecomment-220484748
So is there a better method than that? An answer from a Docker maintainer would be very much welcomed. Thanks!