hDEV Blog

Just my place to write something about my life as an IT Guy

Running in a docker container?

Sometime you need to know, it you are running in a docker container. This can be down with a lock at the control groups /proc/self/cgroup.

Heads up to Control Groups (cgroups) in docker:

Control Groups (cgroups) are a feature of the Linux kernel that allow you to limit the access processes and containers have to system resources such as CPU, RAM, IOPS and network.

In this lab you will use cgroups to limit the resources available to Docker containers. You will see how to pin a container to specific CPU cores, limit the number of CPU shares a container has, as well as how to prevent a fork bomb from taking down a Docker Host.

Source: https://dockerlabs.collabnix.com/advanced/security/cgroups/

If you are running in a container you see lines like:

14:name=systemd:/docker/4531c6cdf6e13484be06e3615ebf4721c5...
13:rdma:/
12:pids:/docker/4531c6cdf6e13484be06e3615ebf4721c5...

So just open the file /proc/self/cgroup

// IsRunningInContainer check in cgroup if your are running in a docker container
func IsRunningInContainer() (bool, error) {
	if runtime.GOOS != "linux" {
		return false, nil
	}

	file, err := os.DirFS("/proc/self").Open("cgroup")
	if err != nil {
		return false, err
	}
	defer file.Close()

	isDocker, _, err := isRunningInContainer(file)

	return isDocker, err
}

and look for the keyword docker:

func isRunningInContainer(file fs.File) (bool, string, error) {
	r := bufio.NewReader(file)

	var line string
	var err error
	for {
		line, err = r.ReadString('\n')
		if err != nil && err != io.EOF {
			break
		}

		if strings.Contains(line, "docker") {
			split := strings.Split(line, "/")
			lastSegment := split[len(split)-1]
			return true, strings.TrimSpace(lastSegment), nil
		}

		if err != nil {
			break
		}
	}

	if err != io.EOF {
		return false, "", err
	}

	return false, "", nil
}

Or see my Go Package: https://github.com/dhcgn/dockerdetector

Impressum Datenschutz