Alex Sarafian
Alex Sarafian

Reputation: 674

Detect if process executes inside a Windows Container

It's simple. I would like to detect with code if my process is running inside a windows container. There are examples but they are all for linux based containers.

I'm looking for something unique and explicit to docker that can be used to make a safe conclusion whether a process is executing inside a container hosted windows operating system and not otherwise.

My preferred language is PowerShell but if someone points out the how to detect, I'll port it to PowerShell.

Upvotes: 9

Views: 3999

Answers (4)

pharring
pharring

Reputation: 2046

There's a "ContainerType" registry value under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control.

So:

function Test-IsInsideContainer {
  $containerType = (Get-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Control").ContainerType
  $containerType -ne $null
}

Upvotes: 7

frank koch
frank koch

Reputation: 1178

New readers can skip ahead to the part marked with "Update" which contains the accepted solution.

A quick check with whoami on the command prompt showed that the combination of domain and username that is used inside a container seems to be rather unusual. So I used this code to solve the problem:

function Test-IsInsideContainer {
  if( ($env:UserName -eq "ContainerAdministrator") -and ($env:UserDomain -eq "User Manager") ) {
    $true
  }
  else {
    $false
  }
}

Update: Another option is to check if the service cexecsvc exist. An internet search did not yield much information about this service, but its name (Container Execution Agent) suggests that it only exists inside of containers (which I verified with some quick test on Win10 and a Server2016 Docker-host). So maybe this code meets your requirements (I am a newbie in Powershell):

function Test-IsInsideContainer {
  $foundService = Get-Service -Name cexecsvc -ErrorAction SilentlyContinue
  if( $foundService -eq $null ) {
    $false
  }
  else {
    $true
  }
}

Upvotes: 7

Dominique
Dominique

Reputation: 1

As of Docker 17.06 onward you could use the DNS entry docker.for.mac.localhost and docker.for.mac.localhost to determine if the container runs on a mac or windows host. if none of these host names can be pinged you might safely assume its a linux host. This will probably not work for Swarms.

I am not an expert in Bash but an example could look like this.

#!/bin/bash

ping -c 1 docker.for.mac.localhost &>/dev/null
if [ $? -eq 0 ]; then
    echo "Mac Host"
fi

ping -c 1 docker.for.win.localhost &>/dev/null
if [ $? -eq 0 ]; then
    echo "Windows Host"
fi;

I hope this helps you writing the script in PowerShell and please do share for whenever I need something like this in Windows.

Upvotes: -2

Gregory Suvalian
Gregory Suvalian

Reputation: 3832

Will below work? PS C:\> (Get-NetAdapter).Name -match "container" True

Upvotes: -1

Related Questions