Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use variables in Dockerfile

I am trying to use variables inside a Dockerfile. I don't understand why the occurrence $MyVariable is never replaced by the value.

I build my image using:

docker build --build-arg PYTHON_VERSION=python-3.8.8.amd64 -t succeeds .

In my dockerfile I have the following code :

# escape=`
FROM mcr.microsoft.com/windows/servercore:1909
ARG PYTHON_VERSION=python-3.8.1.amd64
ENV PYTHON=C:\$PYTHON_VERSION

RUN echo $PYTHON_VERSION
RUN echo ${PYTHON_VERSION}
RUN echo PYTHON_VERSION

The shell respectively print:

$PYTHON_VERSION
${PYTHON_VERSION}
PYTHON_VERSION

The documentation suggests:

An ARG declared before a FROM is outside of a build stage, so it can’t be used in any instruction after a FROM. To use the default value of an ARG declared before the first FROM use an ARG instruction without a value inside of a build stage:

ARG VERSION=latest FROM
$VERSION 
ARG VERSION 
RUN echo $VERSION > image_version 

But I am clearly not getting the same result. Shall I add something in the docker command to use the variables?

like image 249
Teddy Avatar asked May 07 '26 04:05

Teddy


1 Answers

You need to know that ARG is not available in the container. While ENV is available in the container. Please see this good diagram from here: enter image description here

So in your case you need to use the ENV name and not the ARG name like this:

# escape=`
FROM mcr.microsoft.com/windows/servercore:1909
ARG PYTHON_VERSION=python-3.8.1.amd64
ENV PYTHON=$PYTHON_VERSION

RUN echo $PYTHON
like image 157
RafaelJan Avatar answered May 09 '26 00:05

RafaelJan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!