Docker containers and namespaces

November 12, 2021 - Reading time: 2 minutes

The name or identifier of each container represents a different namespace. This includes the PID namespace:

test@localhost: sudo docker run -d --name ns1 busybox /bin/sh -c "sleep 50000" 
c697ca05f26d149ae2f8d4cd3f69d337eca9780bf3b6fa7966a2cada9e38db02
test@localhost: sudo docker run -d --name ns2 busybox /bin/sh -c "sleep 90000" 
3d47c92028f861ecbba3fa079c0d7009aee558f953ce8ee534fdd349fb0bd403
# List processes inside each container:
test@localhost: sudo docker exec ns1 ps 
PID   USER     TIME  COMMAND
    1 root      0:00 sleep 50000
   14 root      0:00 ps
test@localhost: sudo docker exec ns2 ps 
PID   USER     TIME  COMMAND
    1 root      0:00 sleep 90000
    7 root      0:00 ps

We can specify the a different namespace for the PID using --pid. To share the same namespace as the host:

test@localhost: sudo docker run --pid host busybox ps | grep sleep
 6206 root      0:00 sleep 50000
 6290 root      0:00 sleep 90000
 6708 1000      0:00 grep sleep

The first 12 chars of the container id (1024 bit number) can be used interchangeably with the container name:

est@localhost: sudo docker ps --no-trunc
CONTAINER ID                                                       IMAGE     COMMAND                      CREATED          STATUS          PORTS     NAMES
3d47c92028f861ecbba3fa079c0d7009aee558f953ce8ee534fdd349fb0bd403   busybox   "/bin/sh -c 'sleep 90000'"   13 minutes ago   Up 13 minutes             ns2
c697ca05f26d149ae2f8d4cd3f69d337eca9780bf3b6fa7966a2cada9e38db02   busybox   "/bin/sh -c 'sleep 50000'"   13 minutes ago   Up 13 minutes             ns1
test@localhost: sudo docker exec 3d47c92028f8 ps
PID   USER     TIME  COMMAND
    1 root      0:00 sleep 90000
   30 root      0:00 ps

The CID can be written to a file during create or run

test@localhost: sudo docker create --cidfile /var/tmp/web.cid nginx 
2f7863c7fc126df665b43913bbe93685cb18733d5f9912c144f96905e4ad630d
test@localhost: cat /var/tmp/web.cid 
2f7863c7fc126df665b43913bbe93685cb18733d5f9912c144f96905e4ad630