Using ARG in FROM in dockerfile

Viewed 2789

Problem statement: I need to pull docker(projectA and projectB) from two different urls based on the arg provided.

ARG url=docker-local.artifactory.com/projectA #By default its for A.
RUN echo ${url}
FROM $url

Ideal Solution:

docker build -t hello . should build docker of project A

docker build --build-arg url="docker-local.artifactory.com/projectB" -t hello . should build docker of project B.

Current Issue:

"base name ($url) should not be blank"
2 Answers

Using the docs for reference, if you want to use ARG before FROM, don't use anything in-between. See this section for details.

This minimal Dockerfile works:

ARG url=docker-local.artifactory.com/projectA 
FROM $url

Built using this command with a build arg:

docker build -t from --build-arg url=alpine:3.9 .
[+] Building 0.1s (5/5) FINISHED
 => [internal] load build definition from Dockerfile                                                               0.0s
 => => transferring dockerfile: 116B                                                                               0.0s
 => [internal] load .dockerignore                                                                                  0.0s
 => => transferring context: 2B                                                                                    0.0s
 => [internal] load metadata for docker.io/library/alpine:3.9                                                      0.0s
 => CACHED [1/1] FROM docker.io/library/alpine:3.9                                                                 0.0s
 => exporting to image                                                                                             0.0s
 => => exporting layers                                                                                            0.0s
 => => writing image sha256:352159a49b502edb1c17a3ad142b320155bd541830000c02093b79f4058a3bd1                       0.0s
 => => naming to docker.io/library/from

The docs also show an example if you want to re-use the ARG value after the first FROM command:

ARG url=docker-local.artifactory.com/projectA 
FROM $url
ARG url
RUN echo $url

Using the following build file,

ARG VERSION=busybox:latest
FROM $VERSION
ARG VERSION
RUN echo $VERSION

Running with the default value

docker build -t test .
Sending build context to Docker daemon  16.38kB
Step 1/4 : ARG VERSION=busybox:latest
Step 2/4 : FROM $VERSION
latest: Pulling from library/busybox

Running with value changed during build

docker build -t test --build-arg VERSION="ubuntu:20.04" .
Sending build context to Docker daemon  16.38kB
Step 1/4 : ARG VERSION=busybox:latest
Step 2/4 : FROM $VERSION
20.04: Pulling from library/ubuntu
Related