I've only seen examples of using COPY to copy files between stages of a multi stage Dockerfile, but is there a way to simply copy an ENV variable? My use case is to start out with a git image to just to get the commit hash that will be part of the build. The image I'm later building with hasn't got git.
I realise I could just pipe out the git hash to a file and use COPY but I'm just wondering if there's a cleaner way?
A multistage build allows you to use multiple images to build a final product. In a multistage build, you have a single Dockerfile, but can define multiple images inside it to help build the final image.
With multi-stage builds, you use multiple FROM statements in your Dockerfile. Each FROM instruction can use a different base, and each of them begins a new stage of the build. You can selectively copy artifacts from one stage to another, leaving behind everything you don't want in the final image.
Let's say we have two Dockerfiles, one for building the backend and another for building the frontend. We can name them appropriately and invoke the build command two times, each time passing the name of one of the Dockerfiles: $ docker build -f Dockerfile.
COPY is a docker file command that copies files from a local source location to a destination in the Docker container. ADD command is used to copy files/directories into a Docker image. It only has only one assigned function. It can also copy files from a URL.
You got 3 options: The "ARG" solution, the "base" solution, and "file" solution.
ARG version_default=v1
FROM alpine:latest as base1
ARG version_default
ENV version=$version_default
RUN echo ${version}
RUN echo ${version_default}
FROM alpine:latest as base2
ARG version_default
RUN echo ${version_default}
another way is to use base container for multiple stages:
FROM alpine:latest as base
ARG version_default
ENV version=$version_default
FROM base
RUN echo ${version}
FROM base
RUN echo ${version}
You can find more details here: https://github.com/moby/moby/issues/37345
Also you could save the hash into a file in the first stage, and copy the file in the second stage and then read it and use it there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With