There are 3 places that I see that might work so far, each have advantages & disadvantages:
echo $HOSTNAME
or hostname
cat /proc/self/cgroup
cat /proc/self/mountinfo
$HOSTNAME
is easy, but it is partial, and it will also be overwritten to pod name by K8s.
/proc/self/cgroup
seems working with cgroupV1 but won't be there hosted in cgroupV2.
/proc/self/mountinfo
will still have the container id for cgroupV2, however, the mount point will have different values by different container runtimes.
- For example, in docker engine, the value looks like:
678 655 254:1 /docker/containers/7a0144cee1256c539fab790199527b7051aff1b603ebcf7ed3fd436440ef3b3a/resolv.conf /etc/resolv.conf rw,relatime - ext4 /dev/vda1 rw
- In
ContainerD
(K8s default engine lately), it looks like:
1733 1729 0:35 /kubepods/besteffort/pod3272f253-be44-4a82-a541-9083e68cf99f/7a0144cee1256c539fab790199527b7051aff1b603ebcf7ed3fd436440ef3b3a /sys/fs/cgroup/blkio ro,nosuid,nodev,noexec,relatime master:17 - cgroup cgroup rw,blkio
Also, the biggest problem for all above is that they are all implementations, there's no abstraction and they all could be changed over time.
There is an effort to make it standard and I think it is worth watching:
https://github.com/opencontainers/runtime-spec/issues/1105