Skip to content
Advertisement

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

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…

Advertisement

Answer

I think the preferred way to do this is through environment variables. If you’re creating your Python app from a Dockerfile, you could specify the ‘ENV’ directive:

https://docs.docker.com/engine/reference/builder/#env

Dockerfile:

...
ENV AM_I_IN_A_DOCKER_CONTAINER Yes

which could then be read from your app with something like:

python_app.py:

import os

SECRET_KEY = os.environ.get('AM_I_IN_A_DOCKER_CONTAINER', False)

if SECRET_KEY:
    print('I am running in a Docker container')
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement