Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a variable be used in docker FROM?

Tags:

docker

I am wondering if a env variable can be used in a docker from? Reason for this is to control the tagging. For example, say I have this line in my Dockerfile:

From myApp 

What I want is this:

From myApp:${VERSION} 

This way I can say docker build . myApp --build-arg VERSION=9

The process to build docker images for this app is the same. I don't want to have Dockerfiles that are almost identical just to use a different base image.If I want to build version 9, it should use version 9 of the base image.

like image 256
CodyK Avatar asked Apr 11 '16 18:04

CodyK


People also ask

Can we use variable in Dockerfile?

You can use ARG variable defaultValue and during the run command you can even update this value using --build-arg variable=value . To use these variables in the docker file you can refer them as $variable in run command.

Can an ARG variable on Dockerfile be used by the running container?

Running containers can't access values of ARG variables. This also applies to CMD and ENTRYPOINT instructions which just tell what the container should run by default.

How do I pass environment variables to Docker containers?

With a Command Line Argument The command used to launch Docker containers, docker run , accepts ENV variables as arguments. Simply run it with the -e flag, shorthand for --env , and pass in the key=value pair: sudo docker run -e POSTGRES_USER='postgres' -e POSTGRES_PASSWORD='password' ...

What is from in Dockerfile?

The FROM instruction specifies the Parent Image from which you are building. FROM may only be preceded by one or more ARG instructions, which declare arguments that are used in FROM lines in the Dockerfile .


2 Answers

Quoting this link :

This is now possible if anyone comes here looking for answers: https://docs.docker.com/engine/reference/builder/#understand-how-arg-and-from-interact

FROM instructions support variables that are declared by any ARG instructions that occur before the first FROM.

ARG  CODE_VERSION=latest FROM base:${CODE_VERSION} CMD  /code/run-app  FROM extras:${CODE_VERSION} CMD  /code/run-extras 
like image 103
Hadrien TOMA Avatar answered Oct 20 '22 01:10

Hadrien TOMA


For at least this docker version this is feasible

docker --version docker version 18.09.8, build bfed4f5 

It requires a preset variable in Dockerfile e.g.

ARG TAG=latest FROM traefik:${TAG} 

Then you can override this preset with the following

docker build --build-arg "TAG=2.2.8" -t my-app:$TAG 

The version number will not show up during build. if you want to test if it works, reference a non-existing version - it will fail with: manifest my-app:version not found.

like image 23
Mandragor Avatar answered Oct 20 '22 01:10

Mandragor