Detect the ID of the docker container your process is running in

Couldn’t find this exact thing elsewhere, so I’m publishing it in case I ever need it again. This trick depends on the fact that docker uses cgroups and the cgroup ID seems to always be equal to the container ID. This probably only works on linux-based docker containers.

import re

def my_container_id():
    '''
        If this process is in a container, this will return the container's ID,
        otherwise it will return None
    '''
    
    try:
        fp = open('/proc/self/cgroup', 'r')
    except IOError:
        return
    else:
        with fp:
            for line in fp:
                m = re.match(r'^.*\:/docker/(.*)$', line)
                if m:
                    return m.group(1)

Leave a Reply