How does one detect if one is running within a docker container within Python? : <p>I was trying to find out if my script was running inside a docker container or not within the python script.</p>

<p>Something like:</p>

<pre><code>if inside_docker():
    do_stuff()
else:
    do_some_other_stuff()
</code></pre>

<p>to do this the only hacky way I found out how to do it is that I can inspect the hostname (with  <code>platform.node()</code>) 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).</p>

<p>Instead I was thinking something a bit more programatic as follows:</p>

<ol>
<li>first detect docker with <code>cat /proc/1/cgroup</code></li>
<li>then compare the name those hierarchies with the docker id/hash.</li>
</ol>

<p>Something like:</p>

<pre><code>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
</code></pre>

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

<pre><code>&gt;&gt;&gt; from subprocess import call
&gt;&gt;&gt; call('from subprocess import call')
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
  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
</code></pre>

<p>any ideas how to fix that?</p>

<hr>

<p>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...</p>
