I am building a Docker image from the OCaml
image ocaml/opam:debian-12-ocaml-5.2
.
During build phase, I need to access the env variable OPAM_SWITCH_PREFIX
which is defined to be /home/opam/.opam/5.2
in the base image above. However, it seems it is not accessible to the commands in my Dockerfile
.
Any idea why is that and how to fix it (I would preferably not hard code the variable in my Dockerfile
nor have to pass it each time with -build-arg
?
When the user's Dockerfile runs commands (e.g., RUN opam ...), these commands are executed in a new shell session within the container during the build process. While the base image sets the environment variable, this setting doesn't automatically persist across all subsequent RUN instructions in the Dockerfile. Each RUN instruction starts a fresh shell, so the variable isn't automatically inherited. You can use ENV instrcution inside Dockerfile. The ENV instruction sets environment variables that persist across all subsequent RUN instructions within the Dockerfile.
FROM ocaml/opam:debian-12-ocaml-5.2
# Set the environment variable using ENV
ENV OPAM_SWITCH_PREFIX="/home/opam/.opam/5.2"
# Now OPAM_SWITCH_PREFIX is available in this RUN command
RUN echo "OPAM_SWITCH_PREFIX is: $OPAM_SWITCH_PREFIX"
# And also in this one
RUN opam switch list