Home > database >  dockerfile copy from with variable
dockerfile copy from with variable

Time:10-08

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

CodePudding user response:

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.

  • Related