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->isDocker() === false) {
throw new \Exception('This helper script can be called only inside Docker container.' . "\n");
}