Docker Community Forums

Share and learn in the Docker community.

Add to path in multistage build

I can not append a variable or absolute path to $PATH in a multistage alpine image.

Tried

ARG VAR=/path/to/append

ENV PATH="$VAR:${PATH}"
ENV PATH "$PATH:$VAR"
ENV PATH="/path/to/append:${PATH}"
ENV PATH "$PATH:/path/to/append"

Then when I look at $PATH in the container in bash the /path/to/append is not there.

I also tried

echo "export PATH=$VAR:${PATH}" >> /root/.bashrc

That did append to the $PATH but the issue is when there are 2 paths only the last one gets appended.

That is

ARG VAR=/path/to/append/1
ARG TWO=/path/to/append/2

echo "export PATH=$VAR:${PATH}" >> /root/.bashrc &&
echo "export PATH=$TWO:${PATH}" >> /root/.bashrc
echo $PATH
/path/to/append/2

Thank you :slight_smile:

To send variable we can use “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: Persisting ENV and ARG settings to all later stages in multi-stage builds · Issue #37345 · moby/moby · GitHub

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.

From what I understand you want to copy the built program into the new docker for multistage build that the output size is smaller. Basically you do not need to send a variable you need to know were you built it in the first image and copy it from there

FROM golang:alpine as gobuilder
RUN apk update && apk add git

COPY sources/src/ $GOPATH/src/folder/
WORKDIR $GOPATH/src/folder/
#get dependencies
RUN go get -d -v
#build the binary
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -a -installsuffix cgo -ldflags="-w -s" -o /go/bin/myGoProgram myGoSource.go

FROM alpine:latest
COPY --from=gobuilder /go/bin/myGoProgram /usr/local/bin/myGoProgram
ENTRYPOINT [“myGoProgram”] # or ENTRYPOINT ["/usr/local/bin/myGoProgram"]

1 Like

Thank you very much :).