Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use --build-arg value in Dockerfile FROM parameter

I'm currently using AWS ECR to host my project images and I need the parameter FROM to be dynamic at Dockerfile according to --build-arg sent from the command line. Example:

$ docker build --build-args region=us-east-1 .

// Dockerfile
FROM aws.ecr.huge.url.${region}/repo:php-apache
WORKDIR /var/www
RUN echo "@@@"

${region} never gets replaced and I get an error saying the image doesn't exist.

If I RUN echo ${region} it works, the problem seems to be with FROM instruction.

Is there any way to achieve that?

like image 824
lrepolho Avatar asked Mar 12 '23 09:03

lrepolho


1 Answers

Updated answer:

With the introduction of multi-stage builds, docker added the ability to provide an ARG before the FROM line. This will look like:

# default to us-east-1
ARG region=us-east-1
FROM aws.ecr.huge.url.${region}/repo:php-apache

Note that ARG's are namespaced. When defined before a FROM line, they are available to the FROM lines. And within a stage, they are available until the end of that stage. If you need to use an ARG in multiple namespaces, you can define it multiple times.


Original answer from before the introduction of multi-stage builds:

This is not supported as you've found, and as documented in the variable expansion limitations:

Environment variables are supported by the following list of instructions in the Dockerfile:

  • ADD
  • COPY
  • ENV
  • EXPOSE
  • LABEL
  • USER
  • WORKDIR
  • VOLUME
  • STOPSIGNAL

as well as:

  • ONBUILD (when combined with one of the supported instructions above)

To workaround this, I suspect you'll need to generate your Dockerfile with an external process first, e.g. with a sed "s/__region__/$region/" <Dockerfile.in >Dockerfile command.

like image 148
BMitch Avatar answered Mar 16 '23 18:03

BMitch