Detecting Docker Environment in Java: A Simple Approach
This code is checking whether the current environment is running within a Docker container. It does this by examining two potential indicators of a Docker environment:
- Checking
/proc/1/cgroup
:- It reads the contents of the
/proc/1/cgroup
file, which typically contains information about the control groups in the system. If the file exists and contains the term “docker” (case-insensitive) in any line,checkCgrpFile
is set totrue
.
- It reads the contents of the
- Checking for
/.dockerenv
file:- It checks for the existence of the
/
directory’s.dockerenv
file. If the file exists,checkDockerenv
is set totrue
.
- It checks for the existence of the
The function then returns true
if either checkCgrpFile
or checkDockerenv
is true
, indicating that the code is running within a Docker container. If both are false
, it implies that the code is not running in a Docker environment.
boolean checkCgrpFile = false;
boolean checkDockerenv = false;
File cgrpFile = new File("/proc/1/cgroup");
if (cgrpFile.exists()) {
try (BufferedReader br = new BufferedReader(new FileReader(cgrpFile))) {
String line;
while ((line = br.readLine()) != null) {
if (line.toLowerCase().contains("docker".toLowerCase())) {
checkCgrpFile = true;
break;
}
}
} catch (IOException e) {
}
}
try {
if (new File("/.dockerenv").exists()) {
checkDockerenv = true;
}
} catch (Exception e) {
checkDockerenv = false;
}
return (checkCgrpFile || checkDockerenv);