Docker How To Tell If You Are In A Container
Better way to check if you are running inside a docker container:
ps -p 1
See the explaination for this further down.
OUTDATED Method: The generally recommended way to check if you are running inside a docker container is to use this commmand:
cat /proc/self/cgroup
I the past this used to give pretty obvious output showing that you are in a docker container. It doesn’t seem to be as clear anymore so this might be a bit trickier.
This is what the output looks like on my Ubuntu 22.04.2 system:
-bash-5.1# cat /proc/self/cgroup
0::/user.slice/user-1000.slice/user@1000.service/app.slice/app-org.gnome.Terminal.slice/vte-spawn-c4d90668-9745-4d14-99b0-0b8f17bbee84.scope
-bash-5.1#
This is what it looks like inside an Docker container with the latest ubuntu image on that same host:
root@50c79e17fabd:/# cat /proc/self/cgroup
0::/
root@50c79e17fabd:/#
Another way to tell would be to just check the number of processes running. Technically, a docker container can contain any number of processes but in practice they usually only have a few ( ex 2 or 3 processes ).
On a normal physical or virtual host you would generally see more than 100 processes running at a time. For example on my Ubuntu desktop I saw 354 processes when I checked:
-bash-5.1# ps -ef | wc -l
354
-bash-5.1#
In a docker container I only saw two processes running.
root@50c79e17fabd:/# ps -ef
UID PID PPID C STIME TTY TIME CMD
root 1 0 0 00:20 pts/0 00:00:00 /bin/bash
root 29 1 0 01:34 pts/0 00:00:00 ps -ef
root@50c79e17fabd:/#
Also note that the process with PID 1 is “/bin/bash”. For a docker container PID 1 will generally be whatever the main command for the image/container was. On a physical/virtual host PID 1 would usually be an init system like systemd.
You can quickly check the processe running with PID 1 using the following two examples:
Physical / Virtual:
-bash-5.1# ps -p 1
PID TTY TIME CMD
1 ? 00:00:07 systemd
-bash-5.1#
Inside Docker container:
root@50c79e17fabd:/# ps -p 1
PID TTY TIME CMD
1 pts/0 00:00:00 bash
root@50c79e17fabd:/#