DevOps | Scripts | Automation

Docker

How to pass multiple arguments to docker run?

Let’s say your docker build image looks something like this,

FROM mcr.microsoft.com/azure-powershell
COPY ./testscript.ps1 tmp/testscript.ps1
ENV Parameter1="Val1"
ENV Parameter2="Val2"
CMD ["pwsh","-File","./tmp/testscript.ps1"]

and the image name for this instance we created is testimage. You want to run this image by passing multiple parameters as mentioned in the image (i.e. Parameter1 and Parameter2).

Val1 and Val2 are the default values for parameters. If we don’t pass any values then it will use them for the respective parameters.

Here we are copying the testscript.ps1 to a container so we grab the passed parameters to the PowerShell file. By passing these parameters we are setting the environment variable for the process so we are using $env:variableName to grab the passed parameters.

testscript.ps1

Write-Host "Passed values to container"
"Parameter1: $($env:Parameter1)"
"Parameter2: $($env:Parameter2)"

Let’s first run docker image without passing any parameters.

docker run testimage

Output:

So it is taking the default values. Let’s pass custom values.

Passing value with ‘-e‘ parameter.

docker run -e Parameter1=Azure -e Parameter2=DevTest testimage

Here we are passing multiple values to an image named testimage. Output will be as below.

There are also other ways to pass the values as mentioned on the docker official website.


Passing value with a local environment variable.

You can also pass values with local environment variables. For example, in PowerShell, we are setting up the below values. You can set accordingly your scripting language/terminal.

$env:param1 = "Parameter1=Azure"
$env:param2 = "Parameter2=DevTest"

Let’s run the docker image

docker run -e $env:param1 -e $env:param2 testimage



Passing values from an environment file

So an environment file is a text file that has the Key value pair of environment variables and they are passed directly to the docker run command with –env-file parameter as mentioned below.

env.txt (name can be anything).

Parameter1=Azure
Parameter2=DevTest

Pass values,

docker run --env-file .\env.txt testimage

Currently file is located in the same directory that we are executing the command. You can provide the full path of the environment file as well.

Loading