admin管理员组

文章数量:1122832

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?

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?

Share Improve this question edited yesterday David Aniebo 2513 silver badges9 bronze badges asked yesterday AbdelghaniAbdelghani 7453 gold badges12 silver badges29 bronze badges 2
  • Environment variable or build arg? The first paragraph talks about env vars, whereas the second paragraph mentions --build-arg) – knittl Commented yesterday
  • At least with environment variables, I cannot reproduce your issue. Environment variables can be referenced in downstream Dockerfiles and in the resulting container. Simple repro: base file: FROM bash ENV myvar=42, build with docker build -t base ., derived file: FROM base RUN echo $myvar. Build output: 42. Run the derived image and enter echo $myvar in the shell – output: 42. – knittl Commented yesterday
Add a comment  | 

1 Answer 1

Reset to default 0

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

本文标签: linuxDockerHow to access base image environment variables at build timeStack Overflow