In a given Dockerfile, I want to set a variable based on content of another ENV variable (which is injected into the container beforehand, or defined within the Dockerfile)
I’m looking at something like this
FROM centos:7
ENV ENABLE_REMOTE_DEBUG "true"
ENV DEBUG_FLAG=""
RUN if [ "$ENABLE_REMOTE_DEBUG" = "true" ] ; then echo "set debug flag" ;export DEBUG_FLAG="some_flags"; else echo "remote debug not set" ; fi
RUN echo debug flags: ${DEBUG_FLAG}
## Use the debug flag in the Entrypoint : java jar ${DEBUG_FLAG} ...
the problem with this Dockerfile is $DEBUG_FLAG
is not properly set (or is not being used in the next line? ) … since output is empty:
debug flags:
What am I missing here? (I prefer not to call external bash script)
2
Answers
You cannot set environment variables using
export
inRUN
instruction and expect to them to available in next instruction. Only filesystem changes created byRUN
instruction are persisted. Other stuff like environment variables etc are discarded.You should move the logic to a shell script.
Let’s take a look at what’s going on when a Dockerfile is used to build a Docker image.
Each line, is executed in a fresh container. The resulting container state, after the line has been interpreted, is saved in a temporary image and used to start a container for the next command.
This temp image do not save any state apart from the files on disk, Docker-specific properties like EXPOSE and a few image settings. Temp images has the advantage of fast subsequent builds using cache.
Now come to your question, if you would want to do using RUN instead of writing in shell script, here is a work around
Since the image is based on CentOS, the default shell is bash, thus sourcing your own environment file will work fine. In other shells where source might not work, then reading the file will help.