13

I've search some of the questions already like docker ENV vs RUN export, which explains differences between those commands, but didn't help in solving my problem.

For example I have a script called myscript:

#!/bin/bash
export PLATFORM_HOME="$(pwd)"

And have following lines in Dockerfile:

...
COPY myscript.sh /
RUN ./myscript.sh

I've also tried to use ENTRYPOINT instead of RUN or declaring variable before calling the script, all that with no success.

What I want to achieve is that PLATFORM_HOME can be referenced from other Dockerfiles which use that one as a base. How to do it ?

marknorkin
  • 3,904
  • 10
  • 46
  • 82

3 Answers3

5

There's no way to export a variable from a script to a child image. As a general rule, environment variables travel down, never up to a parent.

ENV will persist in the build environment and to child images and containers.

Dockerfile

FROM busybox
ENV PLATFORM_HOME test
RUN echo $PLATFORM_HOME

Dockerfile.child

FROM me/platform
RUN echo $PLATFORM_HOME
CMD ["sh", "-c", "echo $PLATFORM_HOME"]

Build the parent

docker build -t me/platform .

Then build the child:

→ docker build -f Dockerfile.child -t me/platform-test  .
Sending build context to Docker daemon  3.072kB
Step 1/3 : FROM me/platform
 ---> 539b52190af4
Step 2/3 : RUN echo $PLATFORM_HOME
 ---> Using cache
 ---> 40e0bfa872ed
Step 3/3 : CMD sh -c echo $PLATFORM_HOME
 ---> Using cache
 ---> 0c0e842f99fd
Successfully built 0c0e842f99fd
Successfully tagged me/platform-test:latest

Then run

→ docker run --rm me/platform-test
test
Matt
  • 68,711
  • 7
  • 155
  • 158
  • 4
    +1 To phrase it slightly differently, `RUN` in a Dockerfile executes the command, and upon the exit of that command, the filesystem changes are persisted in a layer of the image being created. Changes to the environment, spawned daemon processes, etc, are not captured in the image. – BMitch Nov 10 '17 at 12:17
3

I think export sets the environment variables for the child processes. So it really doesn't matter if you do RUN or ENTRYPOINT. In reading linux source command not working when building Dockerfile, I feel source command cannot help either.

You need to use ENV if you want to set the environment variables in Dockerfile.

Chun-Yen Wang
  • 568
  • 2
  • 10
-1

Just use ENV PLATFORM_HOME=$(pwd) in your Dockerfile. Variable will be accessible in every container you will create from the Dockerfile.

Michal Sipek
  • 536
  • 1
  • 6
  • 23
  • 1
    well, the question is about exporting it from script. i can't using it as ENV, because this script is not mine – marknorkin Nov 10 '17 at 11:07