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

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')

import os, re

path = "/proc/self/cgroup"

def is_docker():
  if not os.path.isfile(path): return False
  with open(path) as f:
    for line in f:
      if re.match("\d+:[\w=]+:/docker(-[ce]e)?/\w+", line):
        return True
    return False

print(is_docker())

The is-docker package for npm suggests a robust approach, ported here to Python 2.6+:

import os
def is_docker():
    path = '/proc/self/cgroup'
    return (
        os.path.exists('/.dockerenv') or
        os.path.isfile(path) and any('docker' in line for line in open(path))
    )

Tags:

Python

Docker