Skip to content
Search

Docker SDK for Python

lastmod 2021-05-09created 2020-12-118 edits

A Python library for the Docker Engine API. It lets you do anything the docker command does, but from within Python apps – run containers, manage containers, manage Swarms, etc.

Checking whether the runtime is on the host or a guest

How to check whether the current runtime is running inside a Docker container or on the host machine. The simple way is to check the cgroup.

# cat /proc/self/cgroup
14:name=systemd:/docker/56bc40d80c17e007026013d2afd48a6e0f80f9ddf93d21ce92a18fc50214090e
13:rdma:/
12:pids:/docker/56bc40d80c17e007026013d2afd48a6e0f80f9ddf93d21ce92a18fc50214090e
11:hugetlb:/docker/56bc40d80c17e007026013d2afd48a6e0f80f9ddf93d21ce92a18fc50214090e
10:net_prio:/docker/56bc40d80c17e007026013d2afd48a6e0f80f9ddf93d21ce92a18fc50214090e
9:perf_event:/docker/56bc40d80c17e007026013d2afd48a6e0f80f9ddf93d21ce92a18fc50214090e
8:net_cls:/docker/56bc40d80c17e007026013d2afd48a6e0f80f9ddf93d21ce92a18fc50214090e
7:freezer:/docker/56bc40d80c17e007026013d2afd48a6e0f80f9ddf93d21ce92a18fc50214090e
6:devices:/docker/56bc40d80c17e007026013d2afd48a6e0f80f9ddf93d21ce92a18fc50214090e
5:memory:/docker/56bc40d80c17e007026013d2afd48a6e0f80f9ddf93d21ce92a18fc50214090e
4:blkio:/docker/56bc40d80c17e007026013d2afd48a6e0f80f9ddf93d21ce92a18fc50214090e
3:cpuacct:/docker/56bc40d80c17e007026013d2afd48a6e0f80f9ddf93d21ce92a18fc50214090e
2:cpu:/docker/56bc40d80c17e007026013d2afd48a6e0f80f9ddf93d21ce92a18fc50214090e
1:cpuset:/docker/56bc40d80c17e007026013d2afd48a6e0f80f9ddf93d21ce92a18fc50214090e

The Python test code is as follows:

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

For reference, a typical host machine (tested on Ubuntu 18.04) looks like this:

# cat /proc/self/cgroup
12:rdma:/
11:devices:/user.slice
10:memory:/user.slice
9:pids:/user.slice/user-1000.slice/session-2259.scope
8:perf_event:/
7:cpuset:/
6:net_cls,net_prio:/
5:freezer:/
4:hugetlb:/
3:blkio:/user.slice
2:cpu,cpuacct:/user.slice
1:name=systemd:/user.slice/user-1000.slice/session-2259.scope
0::/user.slice/user-1000.slice/session-2259.scope

Getting the container ID from inside a container

You can obtain the container ID by checking the cgroup or by using the HOSTNAME environment variable. Neither method is reliable.

How to find the container in GitLab CI:

docker ps -q -f "label=com.gitlab.gitlab-runner.job.id=$CI_JOB_ID" -f "label=com.gitlab.gitlab-runner.type=build"

See also

Favorite site

author Zer0 sitemap