Passing environment variables across stages in docker multistage image

1.8k Views Asked by At

I have a docker image which has 4 lower layers.

I want to reduce the size of my current image layer using multistage, but this causes a loss of environment, port and cmd config properties across the stages. Is there a way to pass on such config variables across stages in Dockerfile.

1

There are 1 best solutions below

2
On

You can do one of the following

Use a base container and set the environment values there

FROM alpine:latest as base
ARG version_default
ENV version=$version_default

FROM base
RUN echo ${version}

FROM base
RUN echo ${version}

Other way is to use ARGS as below. There is some repetition but it becomes more centralised

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}

Note examples copied from https://github.com/moby/moby/issues/37345