[Python] How does one detect if one is running within a docker container within Python?

Discussão em 'Python' iniciado por Stack, Março 6, 2025.

  1. Stack

    Stack Membro Participativo

    I was trying to find out if my script was running inside a docker container or not within the python script.

    Something like:

    if inside_docker():
    do_stuff()
    else:
    do_some_other_stuff()


    to do this the only hacky way I found out how to do it is that I can inspect the hostname (with platform.node()) and if the hostname is not the same as my computer then its not in docker (since hostnames docker are some weird hash or something).

    Instead I was thinking something a bit more programatic as follows:

    1. first detect docker with cat /proc/1/cgroup
    2. then compare the name those hierarchies with the docker id/hash.

    Something like:

    from subprocess import call
    import platform
    hash = call('cat /proc/1/cgroup')
    hostname = hostname = platform.node()
    docker_boolean = does_hostname_contain_docker_hash(hash, hostname) # true or false


    I thought something like that would work but I can't even get to call the cat /proc/1/cgroup without an error. If I am in docker I get the error:

    >>> from subprocess import call
    >>> call('from subprocess import call')
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "/usr/lib/python2.7/subprocess.py", line 523, in call
    return Popen(*popenargs, **kwargs).wait()
    File "/usr/lib/python2.7/subprocess.py", line 711, in __init__
    errread, errwrite)
    File "/usr/lib/python2.7/subprocess.py", line 1343, in _execute_child
    raise child_exception
    OSError: [Errno 2] No such file or directory


    any ideas how to fix that?


    as a side node I was thinking of making my solution portable but docker is suppose to be portable already so if I am in docker this should always work...

    Continue reading...

Compartilhe esta Página