Bool function in PHP to check if you run the script inside docker I had to do a CLI script that does something, I also had to add a validation that checks if it runs inside the Docker. After some research I found a solution that people check some processes via cat /proc/self/cgroup and then grep to search for a docker phrase within.

So I ended-up with this method. It works pretty well. Inside docker it returns true, while on my local mac it returns false.

It's not rocket science however I would like people to take a look and tell me if this is a sufficient method or a completely different approach is better.

private function isDocker(): bool
{
    $processStack = explode(PHP_EOL, shell_exec('cat /proc/self/cgroup'));
    $processStack = array_filter($processStack); // remove empty item made by EOL

    foreach ($processStack as $process) {
        if (strpos($process, 'docker') === false) {
            return false;
        }
    }

    return true;
}


Later call to this script looks like:

if ($this-&gt;isDocker() === false) {
    throw new \Exception('This helper script can be called only inside Docker container.' . "\n");
}
For this simple method, I have a couple thoughts below. Your method seems sufficient; I don't think a completely different approach is necessary, although I question how often this method is called. If it is called more than once per page load/script run, it may be worth memoizing the value once obtained for better performance. 



Good job utilizing the PHP 7 return type declaration.



Because the method utilizes no instance properties or methods, it could be declared as static, and possibly public so other code could use it, though maybe it is best to leave it as private until there is a legitimate need to make it otherwise.



While the logic would need to be reversed, substr_count() could be used instead of strpos(). The difference is likely negligible but you need to ask yourself in which case would you rather have the method return as soon as the string is or isn't found...

    foreach ($processStack as $process) {
        if (substr_count($process, 'docker')) {
            return true;
        }
    }
    return false;