3

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?

GeorgS
  • 741
  • 5
  • 12

2 Answers2

7

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.

GeorgS
  • 741
  • 5
  • 12
0

My solution is very similar to GeorgS's but I had to create an ENV using the ARG in order to get this working e.g. $env:ORACLE_BASE

ARG ORACLE_BASE=C:/apps/oracle/
ENV ORACLE_BASE=${ORACLE_BASE}
COPY instantclient-basic-windows.x64-19.17.0.0.0dbru.zip .
COPY instantclient-sqlplus-windows.x64-19.17.0.0.0dbru.zip .
RUN Expand-Archive -Path instantclient-basic-windows.x64-19.17.0.0.0dbru.zip -DestinationPath $env:ORACLE_BASE ; \
    Expand-Archive -Path instantclient-sqlplus-windows.x64-19.17.0.0.0dbru.zip -DestinationPath $env:ORACLE_BASE ; \
    Remove-Item instantclient-basic-windows.x64-19.17.0.0.0dbru.zip -Force ; \
    Remove-Item instantclient-sqlplus-windows.x64-19.17.0.0.0dbru.zip -Force 
TrojanName
  • 4,853
  • 5
  • 29
  • 41