Allow access to the Docker Engine without admin rights on Windows

Allow access to the Docker Engine without admin rights on Windows

18. Dezember 2018

Allow access to the Docker Engine without admin rights on Windows

If you have been working with Docker on Windows, the following message is probably familiar:

error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.40/containers/json: open //./pipe/docker_engine: The system cannot find the file specified. In the default daemon configuration on Windows, the docker client must be run elevated to connect. This error may also indicate that the docker daemon is not running.

As the message says, there are two likely reasons for this error: 1) Your Docker engine is not running and you need to start it. 2) You are not in an administrator / elevated session and therefore don’t have access to the engine. The reason for requiring an admin session is that the Docker client in the default configuration uses a named pipe to connect to the Docker engine and that named pipe can only be accessed by administrators1. If you want to verify that, run the following in an elevated PowerShell session:

PS C:\Windows\system32> [System.IO.Directory]::GetAccessControl("\\.\pipe\docker_engine") | Format-Table

Path Owner                  Access
---- -----                  ------
     BUILTIN\Administrators NT AUTHORITY\SYSTEM Allow  FullControl...

If you are running this on a Windows 10 machine you need to use "\\.\pipe\docker_engine_windows" instead of "\\.\pipe\docker_engine", but the result should be the same. For understandable reasons some like Waldo(rf) are not happy to always use an elevated prompt for a number of security as well as practical concerns. To avoid this, you can simple allow your user FullControl access to that named pipe. That is unfortunately not as easy as changing ACLs on a directory but I have created a very small PowerShell module to help with that2: dockeraccesshelper, source code is here.

Usage is quite easy: When using it for the first time on a machine, you need to install the module with Install-Module -Name dockeraccesshelper

PS C:\Windows\system32> Install-Module -Name dockeraccesshelper

Untrusted repository
You are installing the modules from an untrusted repository. If you trust this repository, change its
InstallationPolicy value by running the Set-PSRepository cmdlet. Are you sure you want to install the modules from
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "N"): y

After that you can always import the module with Import-Module dockeraccesshelper and then run Add-AccountToDockerAccess <username> to give access to a user. In my case, I use the following command:

PS C:\Windows\system32> Import-Module dockeraccesshelper
PS C:\Windows\system32> Add-AccountToDockerAccess "FUM-GLOBAL\TFENSTER"

Now you can run all your docker commands without needing an admin session

  1. This is only true when running Windows containers on Windows. With Linux containers on Window, a group „docker_users“ is allowed as well. Beats me why this doesn’t work the same for Windows containers on Windows, but I’ll try to find out…
  2. The actual coding was way quicker than understanding how to publish this on the PowerShell Gallery as I had never done that before…

897 Kommentare zu “Allow access to the Docker Engine without admin rights on Windows”

  1. Hi Tobias,

    I can indeed set up a new Docker Image, but I don’t seem to be able to do anything else – like execting any navcontainerhelper cmdlet as non-admin … it fails when it wants to create a session (New-PSSession)

    PS > Get-NavContainerAppInfo
    The input ContainerId f9c32e8840465bd082a1ee9e9129264e385c02dd9cd3b7f805f4a8d3b689b9d0 does not exist, or the corresponding container is not running.
    At C:\Users\ericw\Documents\WindowsPowerShell\Modules\navcontainerhelper\\ContainerHandling\Get-NavContainerSession.ps1:37 char:24
    + … $session = New-PSSession -ContainerId $containerId -RunAsAdministrat …
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : InvalidOperation: (:) [New-PSSession], PSInvalidOperationException
    + FullyQualifiedErrorId : CreateRemoteRunspaceForContainerFailed,Microsoft.PowerShell.Commands.NewPSSessionCommand

    any idea?

    1. I don’t think this is a Docker issue but rather WinRM not allowing you to create a PS session if you are not an administrator. At least I can repro that new-pssession doesn’t work but docker exec -ti $containerid powershell gives me a powershell session in the container.

    1. Thanks for mentioning it, I didn’t know that when I wrote the blog post. Depending on a person’s skillset, calling a PS cmdlet might be easier than editing a JSON file, but of course your solution is probably the better supported one

  2. Hi Tobias,

    Great cmdlet, but i’m having issue that when i restart the docker service it loses the permissions i set. Have you seen this before?

  3. I’m not sure where you are getting your info, but great topic.I needs to spend some time learning much more or understanding more.Thanks for great info I was looking for this information for mymission.Here is my web-site Fran

  4. Септик для дачи под ключ недорого

    Это в целом предоставляет вам гарантию того момента, что автономная канализация работает без перебоев в течение многих лет.
    Автономная канализация – наиболее востребованная часть технических коммуникаций
    Автономная канализация цена под ключ-это сегодня наш профиль
    Наша международная компания занимается не только лишь проектированием и сборкой, профессионалы дополнительно делают последующее сопровождение автономной канализации.
    Большой уровень производства септиков

  5. https://novostroyka63.ru/ – Монолитный фундамент цена

    Создание дома вашей мечты – это оригинальная возможность, спланировать и претворить в жизнь нечто воистину уникальное во всех отношениях. Возведение фундамента – это в целом первоначальная модель ремонта, в процессе которой домик строится. При расчете замена фундамента под старым деревянным домом цена предусматривается весьма много факторов. Средняясумма возведения домов фундамента составляет приблизительно от 10$ за кв.метр . Погреб сможет умножить итоговую стоимость каждого объекта недвижимости, предоставляя необходимое помещение ради организации хранения и порой рабочее пространство. Наша профессиональная команда по конструированию и возведенью фундамент под памятник на кладбище цена может помочь выстроить жилище, о котором вы всегда мечтали. От начала до конца наша специализированная компания в Череповец позаботимся о всех без исключения процессах, чтобы заказчику не довелось тревожиться о деталях. Специализированная международная компания в Киселевск несет юридическую ответственность за проект, а не вы, именно поэтому организация в Борисоглебск имеют интерес в том, затем чтобы довести до конца строительство коттеджа быстрее и эффективнее. Узнайте о сваи винтовые для фундамента цены в вытегре у спспециалистовециалистов корпорации.

  6. I discovered your blog website on google and also check a few of your very early posts. Continue to keep up the great operate. I just extra up your RSS feed to my MSN News Reader. Looking for forward to learning more from you in the future!?