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:

JavaScript

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:

JavaScript

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:

JavaScript

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:

JavaScript

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

python_app.py:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement