Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dockerfile copy from with variable

Is it possible to copy from another image inside a dockerfile, using a variable as parameter of the from flag?

What I would achieve is the following

ARG MY_VERSION
COPY --from=my-image:$MY_VERSION /src /dst

But i always get

invalid from flag value my-image:$MY_VERSION: invalid reference format

like image 394
Federico Bellini Avatar asked Mar 29 '26 19:03

Federico Bellini


1 Answers

You can do what you want, but you need to have a FROM statement identifying the image you want to copy from. Something like this

ARG MY_VERSION
FROM my-image:$MY_VERSION as source
FROM scratch as final
COPY --from=source /src /dst

Replace scratch with the base image you want to use for your new image.

Here's an example to show that it works. Dockerfile:

ARG MY_VERSION
FROM ubuntu:$MY_VERSION as source
FROM alpine:latest
COPY --from=source /etc/os-release /

Build and run with

docker build --build-arg MY_VERSION=20.04 -t test .
docker run --rm test cat /os-release

The output shows

NAME="Ubuntu"
VERSION="20.04.2 LTS (Focal Fossa)"
ID=ubuntu
...

which shows that it has copied a file from the Ubuntu 20.04 image to an Alpine image.

like image 55
Hans Kilian Avatar answered Apr 02 '26 09:04

Hans Kilian



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!