Home > other >  Updating Path multiple times in the same RUN command
Updating Path multiple times in the same RUN command

Time:05-15

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?

CodePudding user response:

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