Search code examples
windowspowershelldockerdockerfilenano-server

How to I expand arguments in a Docker RUN command using Powershell?


I have a Dockerfile that uses a Windows Nano Server base image and uses Powershell as shell:

FROM microsoft/nanoserver
SHELL ["powershell"]

I now want to define a variable (or pass it in via --build-arg) using the ARG command and then use it in a RUN command, but I can't seem to get it to work. I've tried:

ARG mydir=tmp
RUN mkdir %mydir%
RUN mkdir $mydir

But none of these work.

How do I tell docker / powershell to expand my variable correctly?


Solution

  • Arguments passed to a Powershell command run via RUN are not substituted by Docker, but by Powershell itself. They are treated like normal environment variables by Powershell, so the correct syntax is:

    FROM microsoft/nanoserver
    SHELL ["powershell"]
    ARG mydir=tmp
    RUN mkdir $env:mydir
    

    So in the same way you can also expand normal environment variables:

    RUN mkdir $env:LOCALAPPDATA\$env:mydir
    

    Note that this is only valid within the context of a RUN command. With other Docker commands variables still expand using the normal notation:

    COPY ./* $mydir
    

    It's confusing on Windows/Powershell as on Linux containers using a bash shell the notation is the same in both cases.