0

Consider the following Dockerfile. On the last lines, first git is installed, and then something is appended to the path environment variable.

FROM mcr.microsoft.com/windows/servercore:ltsc2022

SHELL ["powershell", "-Command", "$ErrorActionPreference = 'Stop';"]

RUN Invoke-Expression ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))

RUN choco install -y git
RUN [Environment]::SetEnvironmentVariable('Path', $Env:Path + ';C:\my-path', [EnvironmentVariableTarget]::Machine)

After the build completes, the path looks like this, so git was added to the path.

C:\ProgramData\chocolatey\bin;C:\Program Files\Git\cmd;C:\my-path;

Here is an equivalent Dockerfile, but I have made the last lines into a single RUN command for optimization.

FROM mcr.microsoft.com/windows/servercore:ltsc2022

SHELL ["powershell", "-Command", "$ErrorActionPreference = 'Stop';"]

RUN Invoke-Expression ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))

RUN choco install -y git; \
    [Environment]::SetEnvironmentVariable('Path', $Env:Path + ';C:\my-path', [EnvironmentVariableTarget]::Machine)

After the build completes, git is not on the path!

C:\ProgramData\chocolatey\bin;C:\my-path;

Why is this, and how can I fix it?

Magnar Myrtveit
  • 2,432
  • 3
  • 30
  • 51
  • I'm not familiar with PowerShell, but in standard Linux containers and the Bourne shell, environment variable changes in a `RUN` command are lost at the end of that command, and you need to use `ENV` to change the environment. See for example [In a Dockerfile, How to update PATH environment variable?](https://stackoverflow.com/questions/27093612/in-a-dockerfile-how-to-update-path-environment-variable). – David Maze May 12 '22 at 13:02
  • @DavidMaze Good suggestion, but doesn't seem to work. `ENV FOO="bar"` works, but `ENV PATH="bar"` messes something up. An error is issued when using the `path` later. – Magnar Myrtveit May 12 '22 at 13:23
  • ENV does not work in Windows containers: https://github.com/moby/moby/issues/30033 – Magnar Myrtveit May 13 '22 at 07:45

1 Answers1

0

A workaround is to use cmd instead of powershell.

Both the following approaches work:

RUN choco install -y git; \
    cmd /c "setx path '%path%;C:\my-path'"
SHELL ["cmd", "/S", "/C"]
RUN choco install -y git && \
    setx path "%path%;C:\my-path"
SHELL ["powershell", "-Command", "$ErrorActionPreference = 'Stop';"]
Magnar Myrtveit
  • 2,432
  • 3
  • 30
  • 51