How to get docker container ID from within the container with cgroup v2

As Docker supports cgroup v2 since engine version 20.10, it will automatically use it on distributions that have cgroups v2 enabled. The known solutions to get the unique container ID from within the container, do not work anymore.

/ # cat /proc/self/cgroup
0::/

/ # cat /proc/1/cpuset
/

Tried with docker v20.10.8 on Debian 11 with alpine:latest.

Working solutions for cgroup v1: How can I get Docker Linux container information from within the container itself?

As stated in the docker reference, with cgroup v2, the container id is still visible in the filesystem at the following places, but those aren't accessible from the container itself.

/sys/fs/cgroup/memory/docker/<longid>/ on cgroup v1, cgroupfs driver
/sys/fs/cgroup/memory/system.slice/docker-<longid>.scope/ on cgroup v1, systemd driver
/sys/fs/cgroup/docker/<longid/> on cgroup v2, cgroupfs driver
/sys/fs/cgroup/system.slice/docker-<longid>.scope/ on cgroup v2, systemd driver

https://docs.docker.com/config/containers/runmetrics/#find-the-cgroup-for-a-given-container

Edit 1/2021-09-01:

One Workaround is to run the container with the option --cgroupns host. But that requires control over the creation of the container.

$ docker run -it --cgroupns host alpine cat /proc/self/cgroup
0::/system.slice/docker-09ec67119d38768dbf7994d81c325e2267214428a3c2e581c81557e3650863d8.scope

$ docker run -it alpine cat /proc/self/cgroup
0::/

Question:

Is there any way, to get the unique container id from within? (without relying on the container hostname or having to use the docker api to fetch the id)


This seems to work without the need to query to cgroup and without using the value of hostname, which sometimes is not set to the value of container id, for example in gitlab runners with docker executors.

OVERLAY_ID=`cat /proc/self/mountinfo | grep -i overlay | sed -n "s/.\+upperdir\\=\\(.\+\\)\\/diff.\+/\1/p"`
CONTAINER_ID=`docker inspect -f $'{{.ID}}\t{{.Name}}\t{{.GraphDriver.Data.MergedDir}}' $(docker ps -aq) | grep $OVERLAY_ID | sed -n "s/\t\+.\+//p"`
echo $CONTAINER_ID

Thanks @soxfmr and to this How do I identify which container owns which overlay directory?