'Updating Path multiple times in the same RUN command

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?



Solution 1:[1]

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';"]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Magnar Myrtveit