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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)