Dockerfile - How to append PATH using ENV instruction?

Viewed 2977

The ENV instruction sets the environment variable to the value . This value will be in the environment for all subsequent instructions in the build stage


Below instruction:

   ENV PATH=$PATH:$HOME/go/bin

does not append PATH variable

$HOME/go/bin is /root/go/bin

How to append $HOME/go/bin to $PATH? in below docker file

FROM golang:1.14.10
MAINTAINER xyz

ENV GOPATH=

ENV PATH=$PATH:$HOME/go/bin

RUN echo $PATH
3 Answers

Apparently Docker doesn't let you use environment variables defined outside of your Dockerfile within an ENV or ARG declaration.

As a workaround, you can pass the names/directories to your Dockerfile explicitly using ARG:

FROM golang:1.14.10
    
# set default to `root`
ARG USERNAME=root

ENV PATH=$PATH:/$USERNAME/go/bin

RUN echo $PATH

You can then pass the USERNAME via docker build --build-arg USERNAME=myuser

Depending on your usecase you can also do this using a RUN or ENTRYPOINT.

I think the confusion is this: when you say $HOME in ENV, home isn't defined yet. But when you say RUN echo $HOME, home is defined by the shell in the base image.

PATH is working and causing confusion, because it's defined by the base image you're using with FROM.

ENV is used to define default variables for the image that will be built, and that will be accessible in RUN statements. Think of it this way: the Dockerfile can provide variables to the container, but the container cannot provide variables to the Dockerfile.

Really, I would just hardcode in /root if root is the user you want to run from. The variables provided by the build are meant to be defaults if you want to do something fancy and dynamic, you probably are better off injecting a script into your image, and running that.

As per mentioned here in this link

I tried using this format and it worked with me:

ENV gradle=/opt/gradle/gradle-6.6.1/bin
ENV PATH=${gradle}:${PATH}
Related