Passing Arguments to Docker windows container

sridharanprasanna

Prasanna Sridharan

Posted on October 28, 2021

Passing Arguments to Docker windows container

Docker allows passing arguments to as build arguments using following syntax, however note that this is Linux container syntax to use the variables with $ sign within the docker file.

Docker file for Linux container

FROM ubuntu:latest
ARG MYARG=defaultValue
RUN echo "The arg value is : $MYARG"
Enter fullscreen mode Exit fullscreen mode

Build command looks like

docker build --build-arg MYARG=ValueFromOutside
Enter fullscreen mode Exit fullscreen mode

For windows container, the arguments are to be referred like below, i.e wrapped with % symbol. So the similar code as above looks like below when executing for windows container:

Dockerfile for Windows container with default shell.

FROM mcr.microsoft.com/windows/servercore:20H2-KB4598242
ARG MYARG=PS
RUN echo "%MYARG%"

RUN powershell.exe -Command \
  $ErrorActionPreference = 'Stop'; \
  $ProgressPreference = 'SilentlyContinue'; \
  Invoke-WebRequest -Uri %MYARG% -Method Get -UseBasicParsing;
Enter fullscreen mode Exit fullscreen mode

Build command looks like

docker build --build-arg MYARG=www.bing.com .   
Enter fullscreen mode Exit fullscreen mode

Note that it was able to print the value of variable as well as execute some PowerShell command using the argument's value.

Image description

Note that the logic depends completely on the shell that is configured to be used. By default the shell is bash for Linux and CMD for windows. Of course by using the [SHELL] statement in the Dockerfile, one can also set it to powershell in which case the argument will be accessed with following syntax: $env:VARIABLE_NAME. Refer here for more details.

FROM mcr.microsoft.com/dotnet/framework/aspnet:4.8-20210209-windowsservercore-ltsc2019
ARG SOMEURI=defaultvalue
RUN Write-Output $env:SOMEURI

RUN Invoke-WebRequest -Uri $env:SOMEURI -Method Get -UseBasicParsing;
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
sridharanprasanna
Prasanna Sridharan

Posted on October 28, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related